So im having this weird problem developing my unity football game, it says "Object Reference Not Set To An Instance Of An Object" On The Script Ball On The Line Of 33 and 19. And also on player script on line 55 and 29. Heres My Code For Player And Ball:
Player:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using StarterAssets;
public class Player : MonoBehaviour
{
private StarterAssetsInputs starterAssetsInputs;
private Animator animator;
private ball ballAttachedToPlayer;
private float timeShot = -1f;
public const int ANIMATION_LAYER_SHOOT = 1;
public ball BallAttachedToPlayer { get => ballAttachedToPlayer; set => ballAttachedToPlayer = value; }
// Start is called before the first frame update
void Start()
{
starterAssetsInputs = GetComponent<StarterAssetsInputs>();
}
// Update is called once per frame
void Update()
{
if(starterAssetsInputs.shoot)
{
starterAssetsInputs.shoot = false;
timeShot = Time.time;
animator.Play("Shoot", ANIMATION_LAYER_SHOOT, 0f);
animator.SetLayerWeight(ANIMATION_LAYER_SHOOT, 1f);
}
if(timeShot>0)
{
// shoot ball
if(ballAttachedToPlayer != null && Time.time - timeShot > 0.2)
{
ballAttachedToPlayer.StickToPlayer = false;
Rigidbody rigidbody = ballAttachedToPlayer.transform .gameObject.GetComponent<Rigidbody>();
rigidbody.AddForce(transform.forward * 20f, ForceMode.Impulse);
ballAttachedToPlayer = null;
}
// finish kicking animation
if (Time.time - timeShot > 0.5)
{
timeShot = -1f;
}
}
else
{
animator.SetLayerWeight(ANIMATION_LAYER_SHOOT, Mathf.Lerp(animator.GetLayerWeight(ANIMATION_LAYER_SHOOT), 0f, Time.deltaTime * 10f));
}
}
}
Ball:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ball : MonoBehaviour
{
private bool stickToPlayer;
[SerializeField] private Transform transformPlayer;
[SerializeField] private Transform playerBallPosition;
float speed;
Vector3 previousLocation;
Player scriptPlayer;
public bool StickToPlayer { get => stickToPlayer; set => stickToPlayer = value; }
// Start is called before the first frame update
void Start()
{
playerBallPosition = transformPlayer.Find("Geometry").Find("BallLocation");
scriptPlayer = transformPlayer.GetComponent<Player>();
}
// Update is called once per frame
void Update()
{
if (!StickToPlayer)
{
float distanceToPlayer = Vector3.Distance(transformPlayer.position, transform.position);
Debug.Log(distanceToPlayer);
if (distanceToPlayer < 0.5)
{
StickToPlayer = true;
scriptPlayer.BallAttachedToPlayer = this;
}
}
else
{
Vector2 currentLocation = new Vector2(transform.position.x, transform.position.z);
speed = Vector2.Distance(currentLocation, previousLocation) / Time.deltaTime;
transform.position = playerBallPosition.position;
transform.Rotate(new Vector3(transformPlayer.right.x, 0, transformPlayer.right.z), speed, Space.World);
previousLocation = currentLocation;
}
}
}
This Script Should Have Shot The Ball Away And Play My Kick Animation, But Instead Threw Me A Random Error.