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

Bug NullReferenceException: Object reference not set to an instance of an object

Discussion in 'Scripting' started by GOmZI, Nov 15, 2022.

  1. GOmZI

    GOmZI

    Joined:
    Nov 15, 2022
    Posts:
    1
    I am new to unity and facing some issue with my third game. Its a football game where player takes the ball runs and shoots. the youtube link from which iam learning how to make this game is:

    The error iam facing is :
    NullReferenceException: Object reference not set to an instance of an object
    Ball.Start () (at Assets/Scripts/Ball.cs:27)


    Please help me out!!!!


    Code (CSharp):
    1. using StarterAssets;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using TMPro;
    5. using UnityEngine;
    6.  
    7. public class Ball : MonoBehaviour
    8. {
    9.     // Start is called before the first frame update
    10.     [SerializeField] private Transform transformPlayer;
    11.    
    12.     private bool stickToPlayer;
    13.    
    14.     [SerializeField] private Transform playerBallPosition;
    15.     float speed;
    16.     Vector3 previousLocation;
    17.     Player scriptPlayer;
    18.  
    19.     public bool StickToPlayer
    20.     {
    21.         get=>stickToPlayer;
    22.         set=>stickToPlayer=value;
    23.     }
    24.  
    25.     void Start()
    26.     {
    27.         playerBallPosition=transformPlayer.Find("Geometry").Find("BallLocation");
    28.         scriptPlayer= transformPlayer.GetComponent<Player>();
    29.     }
    30.  
    31.     // Update is called once per frame
    32.     void Update()
    33.     {
    34.         if(!stickToPlayer)
    35.        
    36.         {
    37.             float distanceToPlayer= Vector3.Distance(transformPlayer.position, transform.position);
    38.             if(distanceToPlayer<0.5)
    39.             {
    40.                 stickToPlayer=true;
    41.                 scriptPlayer.BallAttachedToPlayer=this;
    42.             }
    43.         }
    44.         else
    45.         {
    46.             Vector2 currentLocation =new Vector2(transform.position.x,transform.position.z);
    47.             speed =Vector2.Distance(currentLocation,previousLocation)/Time.deltaTime;
    48.             transform.position=playerBallPosition.position;
    49.             transform.Rotate(new Vector3(transformPlayer.right.x,0,transformPlayer.right.z),speed,Space.World);
    50.             previousLocation=currentLocation;
    51.         }
    52.     }
    53. }