简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM