- Home /
How to pass GameObject between classes?
Hello, I am very new to coding. Before posting this question I searched internet quite a bit, but due to my programming ignorance I could not figure this out.
Assume I have 2 classes, attached to 2 different objects. ObjectA has a serialize field with a prefab that must be attached by hand in Inspector. In runtime I want to pass that prefab from ObjectA (or information about which prefab must be used) to ObjectB as GameObject to instantiate it later. The problem is, that in ObjectB class I can't "scan" ObjectA (using GetComponent, FindObjectOfType, etc) due to some other restrictions.
Is there a way to handle this, or I need to consider of using other approaches? Thanks in advance.
Answer by TheSOULDev · Oct 09, 2017 at 10:17 AM
You need to pass the references around. For an example, make a method in the other function which takes the instance of the first script and use the gameobject from that instance. If you're very new to coding, I suggest you first watch all the tutorials in Unity's tutorial section instead of asking questions that have been answered many times before.
Thank you for your answer, but I clearly said that I already searched before posting in my very first sentence. $$anonymous$$ost of the answers about this topic are about using GetComponent or FindObjectOfType, which for me are not available in this particular situation, that is why I asked for help (other approaches). I did not find a way how to pass a gameobject or its reference, from class B to class A, without ability when both classes can "see" each other (which is not my situation: only class B can see class A, but not the other way around).
What I did: an instance of a static class which can be accessed from any other class (so called singleton). And ins$$anonymous$$d of passing gameobject, I declare it.
Also, for newbies like me I must say, that if you are using static class and want to make changes in serializable non-static variables within this class, you need to be sure to make those changes within instance of this class ins$$anonymous$$d of class itself. If you google this topic, you mostly get answers like: "make this variable static", which is nonsense, because I want it to be serializable.
Your answer
Follow this Question
Related Questions
Passing an object of a custom class in order to access its variables 0 Answers
What is the best way to share data across child classes? 1 Answer
Passing a variable by reference in javascript (using a C# script) 1 Answer
Values not moving to Game Over screen or the Game over doesn't somehow work. 0 Answers
Passing variables back and forth in client server environment using RPC 1 Answer