Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

GetComponent on other gameobject not working

So i have a script that sits on the player when i enter a trigger it doesn’t trigger.
It is supposed to add 1 to a variable score that is in a different script but it just doesn’t work.
I tried to test if the Trigger method works and it does so it has to be a problem with the getcomponent or something.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OnTrigger : MonoBehaviour{
    [SerializeField] private GameObject ScoreManagerObject;
    private ScoreManager ScoreManager;

    private void Awake() {
        if (ScoreManagerObject != null){
            ScoreManager ScoreManager = ScoreManagerObject.GetComponent<ScoreManager>();
        }
    }
    private void OnTriggerEnter(Collider other) {
        if (ScoreManager != null){
            //When the trigger is enterd adds 1 to the score
            ScoreManager.score = ScoreManager.score + 1;
            Debug.Log("score " + ScoreManager.score );
        }
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In your Awake() function you try to get the script of the targeted GameObject, but you store the value in a variable instead of your class property

What you have :

private void Awake() {
    if (ScoreManagerObject != null){
        ScoreManager ScoreManager = ScoreManagerObject.GetComponent<ScoreManager>();
    }
}

What you should do :

private void Awake() {
    if (ScoreManagerObject != null){
        this.ScoreManager = ScoreManagerObject.GetComponent<ScoreManager>();
    }
}

This way, the value of ScoreManagerObject.GetComponent<ScoreManager>() will be stored in your class property and your code should now access the if in your OnTriggerEnter() function

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading