Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question NullReferenceException at onTargetObjectWarped

Discussion in 'Cinemachine' started by dtilgner, Jun 27, 2020.

  1. dtilgner

    dtilgner

    Joined:
    May 23, 2020
    Posts:
    5
    Hello,

    I am creating a 2d platformer and using CinemachineVirtualCamera for following the character. Now I got the issue that the camera overflows when I reset my character to the starting position. I found the method OnTargetObjectWarped as my solution. But it doesn't do what I want it to do. I get a NullReferenceException.
    Here's my code:
    Code (CSharp):
    1. public Cinemachine.CinemachineVirtualCamera virtualCam;
    2.  
    3.     public void StartRespawnRoutine(GameObject go)
    4.     {
    5.         ToggleObjectForRespawn(go, false);
    6.         StartCoroutine(RespawnRoutine(go));
    7.     }
    8.  
    9.     IEnumerator RespawnRoutine(GameObject go)
    10.     {
    11.         yield return new WaitForSeconds(RespawnTime);
    12.         Vector3 delta = go.transform.position;
    13.         go.transform.position = RespawnLocation.position;
    14.         delta = go.transform.position - delta;
    15.  
    16.         virtualCam.OnTargetObjectWarped(go.transform, delta);
    17.  
    18.         ToggleObjectForRespawn(go, true);
    19.  
    20.         ResetEnvironment();
    21.     }
    22.  
    23.     void ToggleObjectForRespawn(GameObject go, bool toggle)
    24.     {
    25.         go.GetComponent<SpriteRenderer>().enabled = toggle;
    26.         go.GetComponent<CharacterController2D>().enabled = toggle;
    27.     }
    "NullReferenceException: Object reference not set to an instance of an object" is the error message. I already spent too much time on this issue that is probably pretty obvious. Can someone help me here?
     
  2. Gregoryl

    Gregoryl

    Unity Technologies

    Joined:
    Dec 22, 2016
    Posts:
    7,658
    What line of code is generating the message? You have a null object somewhere. Single-step through your code to find it, or add Debug.Log() messages to narrow it down.
     
  3. dtilgner

    dtilgner

    Joined:
    May 23, 2020
    Posts:
    5
    Thanks for the advice. The 20 approaches of trying to make it work made me blind. I forgot to assign the actual virtual cam to the script in Unity ._.