I am new art this, keep getting NullReferenceException: Object reference not set to an instance of an object..... Where am I going wrong?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class playermovement : MonoBehaviour {
Rigidbody2D rbody;
Animator animated;
// Use this for initialization
void Start () {
rbody.GetComponent<Rigidbody2D>();
animated.GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (movement_vector != Vector2.zero)
{
animated.SetBool("isrunning", true);
animated.SetFloat("input_x", movement_vector.x);
animated.SetFloat("input_y", movement_vector.y);
}
else {
animated.SetBool("isrunning", false);
}
rbody.MovePosition(rbody.position + movement_vector * Time.deltaTime);
}
}
Answer by T_Lavell · Feb 21, 2017 at 06:33 PM
rbody and animated have not been assigned - you have created (declared) variables, but not assigned them any value. During Start(), when you call rbody.GetComponent you are not assigning a value, rather you are trying to access a value. Instead, try
rbody = gameObject.GetComponent< Rigidbody2D>();
and similarly adjust your other code for 'animated' What this will do is tell Unity that when you access rbody, you are actually accessing the component attached to the gameobject running the code ('gameObject' is a shortcut built into the script for this sort of thing).
If you want any more clarification, check out the unity documentation - look for something about accessing components from other gameobjects; you aren't accessing another gameobject yet, but the explanation might make assigning values more understandable.