Nothing is working when using rb.MovePosition

Hello forum, I’m trying to learn about pathfinding and I have a wall and a capsule, the capsule is supposed to walk to the target capsule upon LookAt(Target) but the capsule isn’t moving. I’m not sure why it’s not working, the code looks correct as I’m following from a tutorial online. I’m getting object reference not set to an instance of an object error in unity, Target is set up with the capsules rigidbody. Here is my code -

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AIAgent : MonoBehaviour
{

    public float Speed = 5;
    public Transform Target;
    Rigidbody rb;

    // Start is called before the first frame update
    void Awake()
    {
        rb.GetComponent<Rigidbody>();

    }

    // Update is called once per frame
    void FixedUpdate()

    {
        rb.MovePosition(rb.position + (transform.forward * Time.deltaTime * Speed));
        transform.LookAt(Target);
    }

      void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawLine(transform.position, transform.position+(transform.forward*5));
    }
}

Advice please, thank you.

rb = GetComponent();
rb is not a gameobject. Components are attached to gameobjects.

the rb is attached to the capsule, is this what you mean?

oh ok, i ignored this way to write it. sorry.
Did you drop the target in the field called Target in the inspector?

It’s okay, yup I put it in there. It comes up Target (transform).

This is the correct solution, you’re not setting rb to anything in this line, you need to set it equal to the component

1 Like

The answer is lying right in your console window: you are getting null references.

Make sure your log console selector buttons are enabled. See this graphic:

https://discussions.unity.com/t/733002/10

https://discussions.unity.com/t/804947/4

As others have pointed out above, you must initialize rb, otherwise it will be null.

When you have a null reference, STOP ALL OTHER WORK AND FIX IT! This is not an opinion or optional. It is mandatory otherwise you are wasting time. Here is how to fix null reference errors:

The answer is always the same… ALWAYS. It is the single most common error ever.

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:

  • drag it in using the inspector
  • code inside this script initializes it
  • some OTHER external code initializes it
  • ? something else?

This is the kind of mindset and thinking process you need to bring to this problem:

https://discussions.unity.com/t/814091/4

Step by step, break it down, find the problem.

Here is a clean analogy of the actual underlying problem of a null reference exception:

https://discussions.unity.com/t/840647/7

Oh, since VS did not underlined the statement in my test and suggested to use “_=” i supposed it was correct … but it’s not.
Thank you for the confirmation RadRedPanda.

Excellent all, thank you for the help.

VS can only detect syntactical errors, but it’s not smart enough to predict what errors will occur when you actually execute the code. In this case, the line of code was technically correct before, but it just didn’t do what you wanted. :wink:

One other problem, it’s coming up i’ve not initialised my waypoints list, but I have. Here is what the application looks like, the blocks are a path, and the code is below.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AIPath : MonoBehaviour
{
// Start is called before the first frame update
public List Waypoints;
[ContextMenu(“Create Path”)]
void CreatePath()
{
Waypoints = new List();
Waypoints.AddRange(GetComponentsInChildren());
Waypoints.Remove(this.transform);
}
void OnDrawGizmos()
{
Gizmos.color = Color.red;
if(Waypoints != null && Waypoints.Count > 0)
{
for(int i = 1; i < Waypoints.Count; i++)
{
Gizmos.DrawLine(Waypoints[i - 1].position, Waypoints*.position);*
}
Gizmos.DrawLine(Waypoints[0].position, Waypoints[Waypoints.Count-1].position);
}
}
}

Use code tags like you did in your first post. It’s much harder to read your code when you copy-paste it raw into forum.

It looks like you initialize your waypoint list in a method called CreatePath(), but where and when are you calling CreatePath?

Hello, i’m calling it in FixedUpdate. Also trying to use AiPath to create the path but its coming up red. Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AIAgent : MonoBehaviour
{

    public float Speed = 5.0f; //speed of player
    public Transform Target; //target object, other capsule
    Rigidbody rb;
    public AIPath AIpath; //not PathCreator or PathMaker
    List<Transform> path { get { return AIPath.Waypoints; } }

    //A sub main
    void Awake()
    {
        rb = GetComponent<Rigidbody>();

    }

    // FixedUpdate is more dynamic
    void FixedUpdate()

    {

        rb.MovePosition(rb.position + (transform.forward * Time.deltaTime * Speed)); //Move player
        transform.LookAt(Target); //Point in direction of targer
    }

      void OnDrawGizmos() //Direction gizmo
    {
        Gizmos.color = Color.red;
        Gizmos.DrawLine(transform.position, transform.position+(transform.forward*5));
    }
}

My Path code: 

[code=CSharp]using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AIPath : MonoBehaviour
{
    // Start is called before the first frame update

    public List<Transform> Waypoints;

    [ContextMenu("Create Path")]
   
    void CreatePath()
    {
        Waypoints = new List<Transform>();
        Waypoints.AddRange(GetComponentsInChildren<Transform>());
        Waypoints.Remove(this.transform);
    }

    void FixedUpdate()
    {
        CreatePath();
    }

    void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        if(Waypoints != null && Waypoints.Count > 0)
        {
            for(int i = 1; i < Waypoints.Count; i++)
                {
                Gizmos.DrawLine(Waypoints[i - 1].position, Waypoints[i].position);
            }
            Gizmos.DrawLine(Waypoints[0].position, Waypoints[Waypoints.Count-1].position);
        }
    }

}

[/code]

Well, I’m guessing that OnDrawGizmos is probably running before FixedUpdate runs the first time. try adding a call to CreatePath in Awake() so it runs before everything else.

By the way, why are you calling it in FixedUpdate, rather than Start or Awake? Are the waypoints constantly changing?

You were right, though nothing is happening on screen at the moment because im not finished with it. Turns out my function Steer() does not exist in the current context? But it has been created and referred to, there should be a path too in the unity editor with script where I can drag it but it’s not there. Please help, thank you for your patience everyone.

Ai Agent code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AIAgent : MonoBehaviour
{

    public float Speed = 5.0f; //speed of player
    public Transform Target; //target object, other capsule
    int currentWaypoint = 0;
    bool obstructed;
    Rigidbody rb;
    public AIPath AIpath; //not PathCreator or PathMaker
    List<Transform> path { get { return AIpath.Waypoints; } }

    //A sub main
    void Awake()
    {
        rb = GetComponent<Rigidbody>();

    }

    // FixedUpdate is more dynamic
    void FixedUpdate()

    {
        if (!obstructed)
        {
            Steer();
        }
        else
        {
            // Avoidance();
        }
        move();
    }

    void Steer()
    {
        Vector3 Targetdirection = path[currentWaypoint].position - rb.position;
        Vector3 newDirection = Vector3.RotateTowards(transform.forward, Targetdirection, Time.fixedDeltaTime, 0);
        transform.rotation = Quaternion.LookRotation(newDirection);
    }

    void move()
    {

        rb.MovePosition(rb.position + (transform.forward * Time.deltaTime * Speed));
    }

    void OnDrawGizmos() //Direction gizmo
    {
        Gizmos.color = Color.red;
        Gizmos.DrawLine(transform.position, transform.position+(transform.forward*5));
    }
}

Path:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AIPath : MonoBehaviour
{
    // Start is called before the first frame update

    public List<Transform> Waypoints;
    int currentWaypoint = 0;
    Rigidbody rb;
    [ContextMenu("Create Path")]
   
    void CreatePath()
    {
        Waypoints = new List<Transform>();
        Waypoints.AddRange(GetComponentsInChildren<Transform>());
        Waypoints.Remove(this.transform);
    }

    void Awake()
    {
        CreatePath();
    
    }

    void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        if(Waypoints != null && Waypoints.Count > 0)
        {
            for(int i = 1; i < Waypoints.Count; i++)
                {
                Gizmos.DrawLine(Waypoints[i - 1].position, Waypoints[i].position);
            }
            Gizmos.DrawLine(Waypoints[0].position, Waypoints[Waypoints.Count-1].position);
        }
    }

}

All right, thanks :slight_smile:

Really need help on this one, as i’m working towards an AI class next year january.

Both of these problems sound like AIAgent is just not compiling for some reason. Are there any other errors in the Console?