- Home /
How do I spawn an object under another moving object at random in C#?
So I have an chicken moving left and right, and I want to spawn eggs at random times under it. How can I do this? I know the concept for doing it, that much is obvious; Get the location of the chicken. Instantiate an egg prefab with the same location of the chicken, just with a lower y value. Then just put it in an infinite loop with a random time delay... The problem is I have no idea how to do most of this because I am brand new to Unity.
If there is someone that could help me, that would be awesome!
By the way, the game I am making is rendered in 3D, but it is essentially a 2D game because the objects have restrictions in the x direction.
Answer by Rocketman_Dan · Oct 09, 2017 at 05:17 AM
Sounds like conceptually you have it but need help learning the C# required?
For spawning an egg:
public class EggDrop : Monobehaviour
{
public GameObject eggPrefab; //this is your egg, assign it in the editor
float dropDelay = 0;
void Update()
{
if(dropDelay > 0)
{
dropDelay -= Time.deltaTime;
}
else
{
Instantiate(eggPrefab, transform.position, transform.rotation)
dropDelay = Random.Range(1.0f, 5.0f); //sets the time till next drop
}
}
}
For moving the chicken back an forth linearly you need a sin wave. Play around with the parameters for a better result, this is a a rough copy of what you'll need.
public class ChickenMove : Monobehaviour
{
public float speed = 5; //use this in the inspector to set the speed at which it moves
void Update()
{
gameObject.transform.position.x = Mathf.Sin(Time.time * speed);
}
}
You can do mathematical operation on the right sight of that equation to change where it is. Make it a child of an empty gameObject if you want to more easily place it. That would mean it uses it's local position and should go from minus 1 to plus 1 in the x value where the parent object is. To get more than 1 unit worth of movement add a multiplier like Mathf.Sin(Time.time * speed) * 3;
would make it go between -3 and +3.
If you don't understand any part of this just ask. It's better have it explained so you know why it works than to always have to ask with similar problems. Also point out any mistakes I made. I'm going from memory but the logic should be sound even if there's something I'm missing in the code. If there's a serious mistake let me know, I don't want to be spreading misconceptions, I have used the sine wave technique recently but on a scaling object, though the principle should be the same on transform positions, it's been a while since I actually did it for movement.
Your answer
Follow this Question
Related Questions
Prevent object from spawning at a spawn point twice in a row? 3 Answers
Storing the Position Generated by Random.Range 2 Answers
Object Spawning Randomly 0 Answers
What's wrong with my script? 1 Answer