简体   繁体   中英

Unity get a reference of an Object created in a different script

My player object has 4 children objects, called Pawn 1 through 4. When I click on one of them, it becomes selected . When a Pawn is selected, it should glow. Now, the trouble is that in order for glowing to happen properly, each Pawn has to know if it is selected at the moment, or not. I did that part by attaching a

public class PlayerController : MonoBehaviour {
    public GameObject selectedObject;
}

to the Player object, and a script to each Pawn object that, among other things, does this

void Update()
{
    if (transform.parent.gameObject.GetComponent<PlayerController>().selectedObject == 
        gameObject)
    {
        Glow();
    }
}

I can't help but to think that there has to be a better way to do this, as performing a GetComponent on every Update, on every Pawn, for every player seems incredibly wasteful.

Is there a way to get a reference to the selectedObject in Start(), so it keeps getting updated without manually getting it the whole time?

Is there a way to get a reference to the selectedObject in Start(), so it keeps getting updated without manually getting it the whole time?

Cache PlayerController in the Start function.

private PlayerController playerController;

void Start()
{
    playerController = transform.parent.gameObject.GetComponent<PlayerController>();
}

void Update()
{
    if (playerController.selectedObject ==
        gameObject)
    {
        Glow();
    }
}

Why not have the Pawn handle the click interaction and store whether or not it is selected? Then you'd have something like:

if(IsSelected)
    Glow();

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