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. Dismiss Notice

Question Make camera follow object

Discussion in 'Scripting' started by BeBox2017, Jul 20, 2023.

  1. BeBox2017

    BeBox2017

    Joined:
    Jan 22, 2017
    Posts:
    21
    I am creating a game that has loads of objects receiving live input from my computer. As such, there is a varying amount of objects every time I run the scene. I would like to make it so that if I click on one of these objects, it will teleport the camera to that object and follow that object around until I click another button to cancel it out.
    Code (CSharp):
    1. public class CameraFollower : MonoBehaviour
    2. {
    3.  
    4.  
    5.     // Start is called before the first frame update
    6.     void OnMouseDown()
    7.     {
    8.         GameObject cameraaa = GameObject.Find("VR Rig");
    9.         cameraaa.transform.position = this.transform.position;
    10.     }
    11.  
    12. }
    This is my script for this job and it is attached to each game object. VR Rig is the name of my camera (I'm using a XR headset if that matters). It doesnt throw any errors, it just doesnt do anything at all. this.transform.position is supposed to be the location the object is attached to. My end goal is to have something that looks like the following
    void Update()
    (if mouse left button is clicked) {
    x = 1
    }
    while(x = 1) {
    camera follows object
    }
    (if right mouse button is clicked) {
    x = 0
    camera returns to starting position
    }
     
  2. BeBox2017

    BeBox2017

    Joined:
    Jan 22, 2017
    Posts:
    21
    Ive made some more progress thats more promising but I'm getting an error I cant explain.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CameraFollower : MonoBehaviour
    6. {
    7.     void Update() {
    8.  
    9.         if (Input.GetMouseButtonDown(0)) {
    10.             RaycastHit hit;
    11.         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    12.        
    13.         if (Physics.Raycast(ray, out hit)) {
    14.             string name = hit.transform.name;
    15.             Debug.Log(name);
    16.             GameObject aircraft = GameObject.Find(name);
    17.             this.transform.position = aircraft.transform.position;
    18.         }
    19.         }
    20.     }
    21. }
    22.  
    But whenever I click anything the console just writes:
    Object reference not set to an instance of an object on line 11 (Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);)
    Any ideas? Is there an import I'm missing? When I click I am hitting something.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,558
    The answer is always the same... ALWAYS!

    How to fix a NullReferenceException error

    https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

    Three steps to success:
    - Identify what is null <-- any other action taken before this step is WASTED TIME
    - Identify why it is null
    - Fix that

    Beyond that, keep in mind that Camera stuff is pretty tricky... you may wish to consider using Cinemachine from the Unity Package Manager.

    There's even a dedicated forum: https://forum.unity.com/forums/cinemachine.136/
     
  4. BeBox2017

    BeBox2017

    Joined:
    Jan 22, 2017
    Posts:
    21
    Except (from my understanding) what I'm clicking isnt null. All I have is a square and a flat plane, which both have box colliders and their respective mesh renderers. I even tried making a cube inside the scene while its running to no avail, and unfortunately cinemachine wont be able to fufill what I need.
     
  5. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    510
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class SelectAndFollow : MonoBehaviour
    4. {
    5.     Transform target;
    6.     Vector3 offset; // our hover position relative to the target
    7.  
    8.     void Start()
    9.     {
    10.         target=transform;  
    11.     }
    12.  
    13.     void Update()
    14.     {
    15.         Transform cam=Camera.main.transform;
    16.         if (Input.GetMouseButtonDown(0))
    17.         {
    18.             Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition);
    19.             if (Physics.Raycast(ray,out RaycastHit hit,2000f))
    20.             {
    21.                 target=hit.transform;
    22.                 offset=(target.position-cam.position).normalized*15f;   // lets get within 15 meters of target
    23.             }
    24.         }
    25.        
    26.         cam.position=Vector3.Lerp(cam.position,target.position-offset,Time.deltaTime);  // gradually move towards target
    27.         Quaternion rot=Quaternion.LookRotation(target.position-transform.position,Vector3.up);
    28.         cam.rotation=Quaternion.Lerp(cam.rotation,rot,5f*Time.deltaTime);               // gradually look towards target
    29.  
    30.         offset=Quaternion.AngleAxis(-Input.GetAxisRaw("Horizontal")*3f,Vector3.up)*offset;  // rotate the camera offset around the target
    31.         offset=Quaternion.AngleAxis(Input.GetAxisRaw("Vertical")*3f,cam.right)*offset;      // go up and down
    32.         offset*=1f-Input.GetAxis("Mouse ScrollWheel");  // zoom in and out using mouse wheel
    33.     }
    34.  
    35. }
    36.  
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,558
    That only means you didn't find what is null.

    It's not like the computer will find something NOT null and then tell you it's null!! Trust the computer.

    You are still on step #1.
     
  7. BeBox2017

    BeBox2017

    Joined:
    Jan 22, 2017
    Posts:
    21
    Okay then Ill go ahead and ask this, why would a cube or sphere be null? They have no scripts attached, their only modifiers are mesh renderer and cube/sphere colliders.
     
  8. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,558
    Code (csharp):
    1. GameObject cube = GameObject.CreatePrimitive( PrimitiveType.Cube);
    2.  
    3. cube = null;
    4.  
    5. cube.SetActive(false);  // nullref
    And yet you'll notice a fully-formed cube still in scene, and yet cube is null!

    Next question: have you actually found what is null, printed it to Debug.Log() and verified?
     
  9. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,558
    ALSO... you want nullrefs? because this is how to get nullrefs.

    Remember the first rule of GameObject.Find():

    Do not use GameObject.Find();

    More information: https://starmanta.gitbooks.io/unitytipsredux/content/first-question.html

    More information: https://forum.unity.com/threads/why-cant-i-find-the-other-objects.1360192/#post-8581066

    In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY.

    If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way(tm) success of accessing things in your game.
     
  10. BeBox2017

    BeBox2017

    Joined:
    Jan 22, 2017
    Posts:
    21

    I've tried adapting my code to look like this still to no avail unfortunately. My new code looks like this:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System;
    5.  
    6. public class CameraFollower : MonoBehaviour
    7. {
    8.  
    9.     Transform target;
    10.     Vector3 offset; // our hover position relative to the target
    11.     void Start()
    12.     {
    13.         target = transform;
    14.     }
    15.     void Update()
    16.     {
    17.  
    18.         if (Input.GetMouseButtonDown(0))
    19.         {
    20.  
    21.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    22.  
    23.             if (Physics.Raycast(ray, out RaycastHit hit, 2000f))
    24.             {
    25.                 string name = hit.transform.name;
    26.                 Debug.Log(name);
    27.                 GameObject aircraft = GameObject.Find(name);
    28.                 this.transform.position = aircraft.transform.position;
    29.             }
    30.         }
    31.  
    32.     }
    33. }
     
  11. BeBox2017

    BeBox2017

    Joined:
    Jan 22, 2017
    Posts:
    21
    Im not creating the objects from a script, simply right clicking in hierarchy and creating a new 3d object. No, I do not know what is null aswell, and to respond to your second response, I tried removing the gameobject.find aswell but that had no effect. How would I print a cube created in the hierarchy's null status?