- Home /
access gameobject from instance of class
Let's say I have GameObjectA that has ComponentA on it. Inside ComponentA I create an instance of ClassB (that preferably does not extend MonoBehaviour). Is there a way that ClassB can reference GameObjectA without passing GameObjectA to the ClassB constructor?
Thanks
Answer by jmgek · Nov 17, 2016 at 01:55 AM
This is extremely confusing, but what I think you're trying to do is reference gameobject A inside the instanced Class B that was created in Class A...
Is there a reason you cant pass it?:
ClassB classb = new ClassB(this.gameObject);
That's the best way, but if you need to (and I find this silly):
class GameManager
{
static GameObject gameObjectA;
void Start()
{
ClassB classB = new ClassB();
gameObjectA = this.gameObject;
}
}
public ClassB
{
GameObject instancedGameObjectA;
void ClassB()
{
instancedGameObjectA = GameManager.gameObjectA;
}
}
There may be a better way, but this is from the top of my head. Good luck!
Thanks for the reply. I know I could pass the gameObject in the constructor and I mentioned that in my question, but I guess I was wondering if there was a cleaner way, so in ClassB saying something like
GameObject gameObjectA = this.instantiatingClass.gameObject;
$$anonymous$$ind of like how you can refer to the base class in a subclass.
Doesn't sound like there is though.
Thanks again
In my second piece of code I'm not passing anything to the constructor, I'm referencing the static gameObject that instanced the current ClassB in the constructor. It's basically what you're asking to do.
To my knowledge you can't instance a class and reference what instanced it in c#. I may be wrong,
Your answer
Follow this Question
Related Questions
How to pass over different scripts, subscribing to the same interface 0 Answers
Assigning class reference dynamically? 1 Answer
Instantiating a class using dragged-in references 0 Answers
How do I reference variables from other class files? 1 Answer
Im not sure why this works, Class referencing & memory question, 1 Answer