The question is answered, right answer was accepted
Null Reference Exception Error
Hello, I keep getting this error in my 2D C# game:
NullReferenceException: Object reference not set to an instance of an object Character.ThrowKnife (Int32 value) (at Assets/Scripts/Character.cs:43) Player.ThrowKnife (Int32 value) (at Assets/Scripts/Player.cs:171)
here is the Character code:
public virtual void ThrowKnife(int value)
{
if (facingRight)
{
GameObject tmp = (GameObject)Instantiate(knifePrefab, KnifePos.position, Quaternion.Euler(new Vector3(0, 0, -90)));
tmp.GetComponent<Knife>().Initialize(Vector2.right);
}
else
{
GameObject tmp = (GameObject)Instantiate(knifePrefab, KnifePos.position, Quaternion.Euler(new Vector3(0, 0, 90)));
tmp.GetComponent<Knife>().Initialize(Vector2.left);
}
}
and here is the Player code:
public override void ThrowKnife(int value)
{
if (!OnGround && value == 1 || OnGround && value == 0)
{
base.ThrowKnife(value);
}
}
Does knifePrefab have a $$anonymous$$nife script?
GameObject tmp = (GameObject)Instantiate(knifePrefab, $$anonymous$$nifePos.position, Quaternion.Euler(new Vector3(0, 0, -90)));
if (tmp.GetComponent<$$anonymous$$nife>() != null) {
tmp.GetComponent<$$anonymous$$nife>().Initialize(Vector2.right);
} else {
Debug.Log("Unable to find $$anonymous$$nife component on tmp");
}
Answer by Brandoboy · Aug 23, 2016 at 12:00 AM
yes, there is a knife script,but it still logs "Unable to find knife component on tmp"
here is the knife script:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody2D))]
public class Knife : MonoBehaviour
{
[SerializeField]
private float speed;
private Rigidbody2D myRigidbody;
private Vector2 direction;
// Use this for initialization
void Start () {
myRigidbody = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
myRigidbody.velocity = direction * speed;
}
public void Initialize(Vector2 direction)
{
this.direction = direction;
}
void OnBecameInvisible()
{
Destroy(gameObject);
}
}
I fixed it! The $$anonymous$$nifePrefab didn't include the script, so i added it and it worked.
Follow this Question
Related Questions
GameObject only spawning 60% of the time (c#) 1 Answer
List remains null after initialisation? 1 Answer
Null Reference in UnityStandardAssets.Utility.WaypointProgressTracker.Update 0 Answers
NullReferenceException when attempting to call a GameObject from within PointerEventData 1 Answer
(C#) Invoke giving null reference exception, crashing unity 0 Answers