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); }
}
Answer by Xesin · May 04, 2016 at 09:39 AM
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);
}
}
Well, it seems to be working except that the object is not lerping but teleporting.
I did just that your script work. The problem is that your script does not do what you intend to do. Do you know how Lerp function works?
Thank you for your help! I found this: https://chicounity3d.wordpress.com/2014/05/23/how-to-lerp-like-a-pro/ and it helped me understand lerp.
Your answer
Follow this Question
Related Questions
Random.Range kepps returing the same value 1 Answer
Instantiating random prefabs gives wrong position 3 Answers
Assign role randomly from array for my online game 2 Answers
continously spanws and overlaps 0 Answers
changing rpm when shifting 1 Answer