Hello so I am getting a null reference exception please help this is my code also by the way getVelocity is a public float function
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Character))]
public class Player_Animator : MonoBehaviour
{
public Animator player;
private Character character;
// Start is called before the first frame update
void Start()
{
player = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (player == null)
{
Debug.LogWarning("No valid animator !");
return;
}
player.SetFloat("Velocity",character.getVelocity());
}
Unity posted the wrong version it was actually velocity.magnitude instead of getVelocity()
I figured it out I set the Character to public and it worked i tried getVelocity as it was more efficient
You’re still the one that posted it. Not “unity.” Any outdated script is on you. You could edit your post right after posting if you see a mistake to show the “fixed” code. However, besides edits for minor typos or catching your own mistakes right after posting, don’t edit posts removing information that can be helpful for other people making mistakes along similar lines, make new corrected posts with your updated script.
He said “set.” “Setting” a variable (also referred to as assignment) is not the same thing as “declaring” the variable. You have the variable “character.” Now, where in your code do you assign something to this variable to make the variable hold a reference to an object and not be a null reference?
But really, though. Kurt’s answer is exactly what you need to do. Go take a look at the specifics of the exception message in Console pane and try and work this out. Self-sufficiency reading error messages and acting upon them is a very valuable skill!
I would suggest reading up on what the difference is in C# between a value type and a reference type. This will be critical to you moving forward using C#.
Reference types by default are NULL. You have to set them to reference (point) to an object of that type. In your case an instance of “Character”. You assign this to your “character” field.
No, Kurt said that you are not setting the variable anywhere. Of course you declared the variable, but variables do not gather values magically. Well serialized variables might, but since the variable is private, it is not serialized. Since you do not assign any value manually, it will stay null.
Anyways, your post is more than confusing. Your title does not match your problem or code at all. Could you please edit the title? Because others will find this thread and hope to get some information on Vector3.magnitude and it’s not even in the code and not talked about at all. Besides that, null reference exceptions can’t even play a role with anything Vector3 related. Vector3 is a value type and can not be null. So if you get a null reference exception, that has to be before you’re working with Vector3.