Script is not getting a reference.

I am trying to make a script that would randomly lerp around an object. Here it is:


using UnityEngine;
using System.Collections;

public class pingpongtest : MonoBehaviour 
{
	void Start()
	{
		float x = Random.Range(-5f,5f);
		float y = Random.Range(-5f,5f);
		Vector3 newPos = new Vector3(x,y,0);
	}
	void Update()
    {
		transform.position = Vector3.Lerp(transform.position,newPos,Time.time);
		InvokeRepeating("Start",3,3);
    }
   
}

Problem is that newPos doesn’t know that I’ve set it as a Vector3 in the start function. What can I do to make this work? I’ve been trying alot of work arounds but none seem to work properly.


EDIT: for some reason my script is glitching so here is a text verison of it in case it glitches again:

using UnityEngine;
using System.Collections;

public class pingpongtest : MonoBehaviour
{
void Start()
{
float x = Random.Range(-5f,5f);
float y = Random.Range(-5f,5f);
Vector3 newPos = new Vector3(x,y,0);
}
void Update()
{
transform.position = Vector3.Lerp(transform.position,newPos,Time.time);
InvokeRepeating(“Start”,3,3);
}

}

First of all. You are trying to call InvokeRepeating inside the Update, this means that this starts a InvokeRepeating each frame. Second thing, you are declaring newPos inside the Start but trying to use this in the Update.

Posible solution:

using UnityEngine;

public class pingpongtest : MonoBehaviour
{
    void Start() {
        InvokeRepeating("UpdatePosition", 3, 3);
    }

    void UpdatePosition() {
        float x = Random.Range(-5f, 5f); 
        float y = Random.Range(-5f, 5f); 
        Vector3 newPos = new Vector3(x, y, 0);
        transform.position = Vector3.Lerp(transform.position, newPos, Time.time);
    }
    
}