Answers for "how to reference a gameobject in unity"

C#
4

gameobject in unity c#

//define "myObject"
//(asign in in inspector)
public GameObject myObject;
//runs when you hit the play button
void Start()
{
  //change the name to "myObjectsNewName"
  myObject.name = "myObjectsNewName";
}
//Note for Unity and C#
Posted by: Guest on September-01-2020
1

reference to a gameobject

//refere a gameobject from the unity editor

Public GameObject ObjectName; //make sure this is public because you will need to assign it in the inspector


Void Start()
{
	//lets say you want to disable the gameobject but want to enable later.
    //you can do this a few ways, one of those ways is to use a bool, and the other is just to do it on the spot, we are going to do it on the spot.
    ObjectName.SetActive(false); //this will disable the gameobject
}
//lets say you want to enable it through a fuction.
public void Yourfunction()
{
	//you can start this function many ways, through a button, from another script or from this 1.
    //we are going to do it from this 1.
	ObjectName.SetActive(true);
}

//lets say if the player clicks 1 than it will get enabled.

public void Update()
{
	if(Input.KetKeyDown("Alpha1"))
    {
    	//this will check if the player clicks 1 if so it will call the function that sets the object to be enabled.
    	YourFunction(); 
    }
}
Posted by: Guest on November-18-2020
1

create gameobject unity

using UnityEngine;
public class InstantiationExample : MonoBehaviour 
{
    // Reference to the Prefab. Drag a Prefab into this field in the Inspector.
    public GameObject myPrefab;

    // This script will simply instantiate the Prefab when the game starts.
    void Start()
    {
        // Instantiate at position (0, 0, 0) and zero rotation.
        Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity);
    }
}
Posted by: Guest on November-29-2020

Code answers related to "how to reference a gameobject in unity"

C# Answers by Framework

Browse Popular Code Answers by Language