Home > database >  GetComponent on other gameobject not working
GetComponent on other gameobject not working

Time:11-25

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 );
        }
    }
}

CodePudding user response:

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

  • Related