Quantcast
Channel: Latest Questions by esitoinatteso
Viewing all articles
Browse latest Browse all 92

Reference an Instance of an Object?C#

$
0
0
Hi there! I've got a question about a specific problem related to a topic which seems to be hard to understand. That topic is .GetComponent<>(); The question may sound silly but before I got overwhelmed by errors I thought I learned [this][1] lesson well... but now I don't know what to think anymore! **And the question is:** **What do I have to do to access/reference/manipulate an instantiated prefab/GameObject/thing?** Now something more specific ( i'm keeping this generic enough so that any answer may easily be understood by others in my same needs): I've got scriptA attached to objectA, scriptB attached to objectB and scriptC attached to objectA. scriptA has a public "slot" in the editor in which i put objectB. This is a simple way to reference another GameObject. Then I put my objectA with its two scripts inside the Hierarchy, so that it exists. *When I execute in scriptA an Instantiate(objectB) I'm making a Clone of that GameObject, am I right? But what if my scriptC tried to access a variable of scriptB?* *I've set up the references "properly", and by properly I mean that I followed the .GetComponent<>(); method. Obviously I get a null reference exception in this case.* *I know that exception is right, it does make sense: the hierarchy contains no objectB so there's not a scriptB either. But the Hierarchy do contains an objectB(Clone), which has a scriptB.* **So what would I have to do to "talk" to that Clone with my scriptC?** I also tried the static workaround, even if it's not smart when you have multiple clones on screen. It didn't worked. *The only thing I managed to do to solve this issue is to put objectB inside the Hierarchy too, thus disabling the Instantiate execution inside scriptA of objectA. This way I just have to make a regular Find & GetComponent with scriptC to access stuff in scriptB. But this is not what I wanted in the first place.* My apologies, I know this argument has been already explained in tons of examples, but I just couldn't get it. Needless to say that a link or some lines of code would be very appreciated. Thanks in advance for your kindness. P.S.: I can provide you my own code if you think that might improve your answers, but it's just a coded version of what I stated above. [1]: http://answers.unity3d.com/questions/550578/cant-understand-getcomponent-c.html

Viewing all articles
Browse latest Browse all 92

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>