Trying to Generate Different Random Values for Position of Game Object Instances [C#]
I am trying to generate different random values for the position of my game object whenever it is re-instantiated. For some reasons, it is not working. Can someone help to see what is wrong? (newPosition is the value that I hope it would be different everytime a new gameobject is generated.)
using UnityEngine;
using System.Collections;
public class KillObjectGenerator : MonoBehaviour
{
public float randomTimeDelay;
private Vector3 newPosition;
public float spawnTime = 3.0f;
public GameObject cloud;
public GameObject lightning;
private float randomX = Random.Range(-8.3f, 0.78f);
void Start()
{
randomTimeDelay = Random.Range(3f, 6f);
// Start calling the Spawn function repeatedly after a delay.
InvokeRepeating("Generator", randomTimeDelay, spawnTime);
}
void spawnNewPosition()
{
newPosition = new Vector3(randomX, 0.18f, 0);
}
void Generator()
{
Instantiate(cloud, newPosition, Quaternion.identity);
Instantiate(lightning, newPosition, Quaternion.identity);
Debug.Log("Spawned a kill object!");
}
}
Answer by Jessespike · Dec 16, 2015 at 07:14 PM
randomX is assigned a random value once during construction. You want a random value for every new spawn position. So why not move the Random assignment to inside of the spawnNewPosition() function?
void spawnNewPosition()
{
randomX = Random.Range(-8.3f, 0.78f);
newPosition = new Vector3(randomX, 0.18f, 0);
}
But I can't put a function inside
Instantiate(cloud, spawnNewPosition(), Quaternion.identity);
because there will be error trying to put a function inside a field that is for vector3.
Then don't put the function inside, call it before:
void Generator()
{
spawnNewPosition();
Instantiate(cloud, newPosition, Quaternion.identity);
You could also just call SpawnNewPosition() just before you instantiate your cloud and lightning gameobjects. Whats key here is the order of which you do things. In a script or any program$$anonymous$$g language the flow of reading and execution is always Top to bottom and left to right, ignoring any operator precedence. You created that function spawnnewposition() but you haven't called it anywhere. That's your problem. You should call it before the call to Generator(), or inside it before the value for newposition is used in the instantiate function. Functions CAN call other functions, in fact invoke(), and Log() are functions themselves.
With the exception of constructors (which is also a kind of function) anything with () following it is a function!
Your answer
Follow this Question
Related Questions
Need help with this code? thanks. 2 Answers
Moving GameObject a specific distance in the Z direction and back again - regardless of rotation 1 Answer
gameobject position lerp 0 Answers
Enemy not facing player when enter rotation orbit 0 Answers
How to properly split string received from server to update Vector3? 2 Answers