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

Attaching Objects using script,not by Dragging?

Discussion in 'Editor & General Support' started by SalmanJaved, Oct 3, 2019.

  1. SalmanJaved

    SalmanJaved

    Joined:
    Sep 12, 2019
    Posts:
    10
    I creat an instance of type GameObject in script. like
    public GameObject NewInstance;

    unity creats an empty tab in inspector with name: New Instance, and i have to attach it a GameObject by dragging or clicking small circle and selecting.

    My Question is it Possible to assign the GameObject to variable NewInstance from C# script directly and not doing it by dragging in Inpector.
    Thanks.
     
  2. MadeFromPolygons

    MadeFromPolygons

    Joined:
    Oct 5, 2013
    Posts:
    3,886
    If its just an object or component in the scene, you can use one of the find methods such as GameObject.Find (https://docs.unity3d.com/ScriptReference/GameObject.Find.html) to get the reference in the "Start" or "Awake" or "OnEnable" method in the monobehaviour :) If its an asset in the project rather than the scene, then its much much more of a pain.

    This is because you have to provide proper full path information, file type etc and the API to do such is a bit of a pain to use compared to a single line find function.
     
  3. SalmanJaved

    SalmanJaved

    Joined:
    Sep 12, 2019
    Posts:
    10
    Thanks , You Solved My Problem.