Thursday, November 16, 2017

c# - Unity prefab script "GameObjects" can't be ones on the scene?


Currently, I have an object on the scene, and one in prefab. I want the prefab's script to reference to the object on the scene through the


public GameObject obj;

code. However, when I tried to add the object in the editor, I cant seem to be able to select any objects from the scene, only ones in prefabs.


I am quite new at unity, so am I missing something really basic here?


Thanks for any help!




Answer



If you have the gameobject with the code attached selected, you can drag the gameobject in the scene using the hierarchy to the inspector.


Confusing I know, here is a picture:


enter image description here


EDIT: Strike that, this is more accurate:


With unity, you can not reference things in the hierarchy from a prefab. You need to somehow add it at runtime. A cheap way to do this is to store 'the gameobject in the scene' in a static variable. For instance something like:


public static GameObject thingonstage;
void Start(){
thingonstage = this.gameobject;
}


Then later, you reference the static global variable to get at it.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...