- Home /
Question by
rbatelaan2 · Jun 23, 2020 at 11:39 PM ·
instantiatequaternionvelocityclonefor-loop
How can I spawn balls in every direction around a source (making a sphere) and then make the balls move away from that source?
I have a code that I put on my source and the ObjectToSpawn is a ball. Unity freezes when I click because something is wrong with my for loops. Also, the spheres all move in the same direction (instead of away from the source) when I don't use for loops.
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design.Serialization;
using UnityEngine;
public class SpawnerSample : MonoBehaviour
{
public Rigidbody ObjectToSpawn;
[SerializeField]
float radius;
void Update()
{
if(Input.GetMouseButton(0))
{
for(int angleY = 0; angleY <= 360; angleY += 45)
{
for(int angleZ = 0; angleZ <= 360; angleY += 45)
{
Spawn(0, angleY, angleZ);
}
}
}
}
void Spawn(int angleX, int angleY, int angleZ)
{
Vector3 direction = Quaternion.Euler(0, angleY, angleZ) * Vector3.one;
Vector3 spawnPosition = transform.position + direction * radius;
Rigidbody Clone;
Clone = Instantiate(ObjectToSpawn, spawnPosition, Quaternion.identity) as Rigidbody;
Clone.velocity = direction.normalized;
}
}
Comment
Answer by UnityedWeStand · Jun 24, 2020 at 12:07 AM
You have an error in your code on line 17:
for(int angleZ = 0; angleZ <= 360; angleY += 45)
You are incrementing angleY instead of angleZ, so angleZ never reaches the condition to terminate the for loop, thus causing Unity to freeze. I imagine you meant to write:
for(int angleZ = 0; angleZ <= 360; angleZ += 45)
Indeed, many freezes in Unity can be attributed to infinite loops.