- Home /
Question by
unity_iKHuxM3URJw_qw · Feb 25, 2020 at 09:17 PM ·
c#unity 2dunityeditorrandom.rangerandomize
Hey! Im a beginner and need help in randomizing. (Im making a 2d game in Unity)
So this is my code which spawns a triangle to one of three points. On the last line (Instantiate(triangle....) I would like to randomize the "triangle" to be triangle, triangle1 or triangle2 and I have no idea how. Please help :)
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class RandomChoose : MonoBehaviour { public Transform[] points; public float InvokeRate = 1.0f; public GameObject triangle; public GameObject triangle1; public GameObject triangle2;
void Start()
{
InvokeRepeating("pickpoints", 1.0f, InvokeRate);
}
void pickpoints()
{
int indexNumber = Random.Range(0, points.Length);
Instantiate(triangle, points[indexNumber].position, triangle.transform.rotation);
}
}
Comment
Answer by unity_ek98vnTRplGj8Q · Feb 25, 2020 at 10:07 PM
Same thing you were doing with the points, just throw each triangle into an array and calculate a random index
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomChoose : MonoBehaviour {
public Transform[] points;
public float InvokeRate = 1.0f;
public GameObject triangle;
public GameObject triangle1;
public GameObject triangle2;
private GameObject[] triList;
void Start () {
triList = new GameObject[3];
triList[0] = triangle;
triList[1] = triangle1;
triList[2] = triangle2;
InvokeRepeating ("pickpoints", 1.0f, InvokeRate);
}
void pickpoints () {
int indexNumber = Random.Range (0, points.Length);
GameObject triangleToSpawn = triList[Random.Range(0, triList.Length)];
Instantiate (triangleToSpawn, points[indexNumber].position, triangle.transform.rotation);
}
}