Access to public variable of instantinated prefab not working
I am creating instance ofmy prefab and i need to set variable in his script but i tried many solution and this is not working. Its my code.
I tried:
GameObject.Find("name").GetComponent()
camera.GetComponent.().someVariable = someNumber;
ScriptName script = (ScriptName) Camera.main.GetComponent("ScriptName");
and nothing... Now my code looks like this :
code of instantinated prefab:
public class Camera_Move : MonoBehaviour {
public int test;
}
code of Level Loader:
public class Level_Generator : MonoBehaviour
{
public GameObject camera1;
public Camera_Move camera_script;
void Start () {
camera1 = Instantiate(camera1, new Vector3(0f, 0f, 0f), Quaternion.identity) as GameObject;
camera_script = camera1.GetComponent(typeof(Camera_Move)) as Camera_Move;
camera_script.test = 100;
}
Answer by Cuttlas-U · Feb 11, 2018 at 04:05 PM
hi ; your problem is you are trying to accesss your prefab not the instantiated object the names are same ;
do it this way :
GameObject cameraCreated = Instantiate(camera1, new Vector3(0f, 0f, 0f), Quaternion.identity) as GameObject;
camera_script = cameraCreated .GetComponent(typeof(Camera_Move)) as Camera_Move; camera_script.test = 100;
I tried this but i have the same error :( NullReferenceException: Object reference not set to an instance of an object Level_Generator.Update () (at Assets/scripts/Level_Generator.cs:51) I thought that can be a problem with main camera but i don`t have access to all objects. Instatninated and added manually to game in the scene.
if u like and have " any desk" app installed or u can install
send your id to my gmail so i can take a look :