Hello, I have a class that needs to be constructed, therefore it cannot inherit from Monobehviour:
public class Speed {
private Controller cont;
public Speed () {
cont = GameObject.FindGameObjectsWithTag ("Player") [0].GetComponent<Controller> ();
}
}
From the above, the Controller component is a script attached to a game object with the tag of “Player”.
How do I get references to other game objects (like Player) from a non-monobehaviour class?
I think what you are asking is how to make a class that doesn’t inherit MonoBehaviour
access GameObject
instances.
There are too many options to count but here are a few.
Change the classes so their public interface allows them to be told about game objects that are important to them.
Create a service locator you can use to make certain important game objects effectively global (be careful with this one).
Create an object that has a field for each important kind of game object and then pass around a reference to that object.
Please could you elaborate on your first suggestion.
How could I amend the above so it can be told about the Player game object?
R1PFake
September 29, 2017, 8:29pm
4
I don’t understand your question, GameObject.FindGameObjectsWithTag is a static method, so it can be called from any class.
3 Likes
You can change the constructor or, better yet, encapsulate the constructor altogether.
Constructor to accept a player:
public class Speed {
private readonly Controller cont;
public Speed(GameObject player) {
this.cont = player.GetComponent<Controller> ();
}
}
Encapsulated constructor:
public class Speed {
private readonly Controller cont;
private Speed(GameObject player) {
this.cont = player.GetComponent<Controller> ();
}
public static Speed GetInstance(GameObject player) {
return new Speed(player);
}
}
1 Like
Maybe I’m misunderstanding your question, but the code you have should work fine. Make sure you actually put the tag “Player” in the Tag field of the Player object if it’s not working.
2 Likes
My bad, the initial code I posted worked. I had assumed you needed to inherit from Monobehaviour to have access to the GameObject class.