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

"The Variable myPlayer of Pivot has not been assigned" Send halp pls

Discussion in 'Getting Started' started by EUBall, Sep 16, 2020.

  1. EUBall

    EUBall

    Joined:
    Sep 10, 2020
    Posts:
    5
    Any ideas boys?

    Muh code:


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. public class Pivot : MonoBehaviour
    5. {
    6.     public GameObject myPlayer;
    7.     private void FixedUpdate()
    8.     {
    9.         Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
    10.         difference.Normalize();
    11.         float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
    12.         transform.rotation = Quaternion.Euler(0f, 0f, rotationZ);
    13.         if (rotationZ < -90 || rotationZ > 90)
    14.         {
    15.             if(myPlayer.transform.eulerAngles.y == 0)
    16.             {
    17.                 transform.localRotation = Quaternion.Euler(180, 0, -rotationZ);
    18.             } else if (myPlayer.transform.eulerAngles.y == 180) {
    19.                 transform.localRotation = Quaternion.Euler(180, 180, -rotationZ);
    20.             }
    21.         }
    22.     }
    23. }
     
  2. EUBall

    EUBall

    Joined:
    Sep 10, 2020
    Posts:
    5
    Also Im a very big beginner so baby language please.
     
  3. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,512
    Welcome to the forums!

    What this error is telling you is that the variable myPlayer inside this script is being accessed without being set. You've declared the variable on line 6, so that's good. You then first access it on line 15 by checking its "transform" property.

    The problem is that the game doesn't know what myPlayer is supposed to be!

    There's two ways to assign references to variables in Unity.
    1. In the editor, click on the file that has this script attached to it. Then click-and-drag the object you want (the Player object, in this case) to the empty field in the Inspector that says My Player.
    2. If the component you want is on the same object as your script, or is in the hierarchy above or below the object you're working on, you can use one of the GetComponent type methods to find the object you need.
    Once you have that object assigned to the variable in your script, that error will go away.
     
    EUBall and JoeStrout like this.
  4. EUBall

    EUBall

    Joined:
    Sep 10, 2020
    Posts:
    5
    Huzza! It works. Thanks my dude.
     
    Schneider21 likes this.