Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Instantiate prefab doesn't assign variables

Discussion in 'Scripting' started by RobLande, Jul 16, 2017.

  1. RobLande

    RobLande

    Joined:
    May 3, 2017
    Posts:
    7
    I try to enable and disable different canvases with a left mouse click on game objects with Raycasts. But I instantiete it from prefabs so it doesnt save the Main Camera and Canvas I want to disable and enable.

    I know how to do it with GameObject:
    Code (CSharp):
    1. cameraCheck = GameObject.FindWithTag( "MainCamera" );
    but GameObject and Canvas/Camera dont have a FindWithTag? So I try FindObjectOfType which gives me all kinds of errors.

    Code (CSharp):
    1. void Start()
    2.     {
    3.         canvasBuilding.enabled = false;
    4.         cameraCheck = FindObjectOfType<Camera>.tag "MainCamera";
    5.         canvasBuilding = FindObjectOfType<Canvas>.tag "Building_01";
    6.     }
    Code (CSharp):
    1. void Start()
    2.     {
    3.         canvasBuilding.enabled = false;
    4.         cameraCheck = Camera.FindObjectOfType<Camera>().tag "MainCamera";
    5.         canvasBuilding = Canvas.FindObjectOfType<Canvas>().tag "Building_01";
    6.     }
    It just all doesnt seem to work.

    Thank you for your time :)
     
  2. JoePatrick

    JoePatrick

    Joined:
    Nov 3, 2013
    Posts:
    118
    First off, you can replace
    Code (CSharp):
    1. cameraCheck = GameObject.FindWithTag( "MainCamera" );
    with
    Code (CSharp):
    1. cameraCheck = Camera.main;
    And if you want to keep track of the objects you're instantiating then just store them when you create them
    eg.
    Code (CSharp):
    1. Canvas canvasBuilding = Instantiate(CanvasPrefab);
     
  3. RobLande

    RobLande

    Joined:
    May 3, 2017
    Posts:
    7
    Thanks! Camera.main; worked!

    Only I would like to set my canvas similar, and call it by its tag. Ive tried
    Code (CSharp):
    1. canvasBuilding = Canvas.FindObjectOfType<Canvas>().GetComponent<BuildingUnitsCanvas>();
    I can't know how to set it up in Start() to the right Canvas I want to enable and disable


    Thank you :)