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

[Help] Assigning gameobject to a variable with mouseclick

Discussion in 'Scripting' started by greburt, Apr 26, 2020.

  1. greburt

    greburt

    Joined:
    Feb 27, 2020
    Posts:
    9
    Hi all,

    Hoping to get some guidance on what I thought would be a pretty straightforward piece of code. The below throws a null reference exception when I click on the instantiated gameobject (cube).

    Code (CSharp):
    1. public class SpawnManager : MonoBehaviour
    2. {
    3.     public GameObject activeCube;
    4.     public GameObject cube;
    5.  
    6.     // Start is called before the first frame update
    7.     void Start()
    8.     {
    9.         InvokeRepeating("CubeSpawn", 0, 5);  
    10.     }
    11.  
    12.     // Update is called once per frame
    13.     void Update()
    14.     {
    15.         if (Input.GetMouseButtonDown(0))
    16.         {
    17.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    18.             RaycastHit hit;
    19.  
    20.             if(Physics.Raycast(ray, out hit))
    21.             {
    22.                 activeCube = hit.transform.gameObject;
    23.                 Debug.Log(activeCube);
    24.             }
    25.         }
    26.     }
    27.  
    28.     public void CubeSpawn()
    29.     {
    30.         Instantiate(cube, transform.position, transform.rotation);
    31.     }
    32. }
    It spawns the cubes ok. I was just hoping to set one of them as 'active' for other functions.

    Any help would be appreciated.

    Thank you!
     
  2. Primoz56

    Primoz56

    Joined:
    May 9, 2018
    Posts:
    369
    make sure your cubes have a collider component so rays can find them
     
  3. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,890
    Try the longer form of Raycast.

    Code (csharp):
    1. public LayerMask layersToHit;
    2. public float distance = 1000f;
    3.  
    4. if (Physics.Raycast(ray, out RaycastHit hit, distance, layersToHit))
     
  4. greburt

    greburt

    Joined:
    Feb 27, 2020
    Posts:
    9
    Thanks guys, I figured it out.

    For anyone who experiences a similar issue - my camera was not tagged as "main camera", which is required for Camera.main.