0

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?

2 Answers 2

2

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();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, exactly what I was looking for.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.