Unity C# - Using one gameobject to control other randomly picked gameobjects

2 weeks ago 16
ARTICLE AD BOX

This is my goal. I want to randomly assign gameobjects for other gameobjects to control, but I want for each one to be able to control more than one. Right now, the code will run through an array of gameobjects and randomly assign them another gameobject to control. But with the way that I am doing this, I am unsure of a way to allow each gameobject to control 2 or more other gameobjects.

The below code is 100% working for assigning a single child gameobject to each of the chosen game objects.

Also, I dont want my gameobjects to have the possibility to be assigned the same game object twice which is where I am struggling to figure out a good way to solve this. Or should I try throwing the entire provided code into a loop and let it repeat for how many times that there should be children to the object?

Any help is appreciated

void AssignChildren () { pieces = GameObject.FindGameObjectsWithTag("Piece").OrderBy( go => go.name ).ToArray(); int pieceCount = pieces.Length; Debug.Log (pieceCount); List<int> usedNumbers = new List<int>(); int newNumber; for (int iter = 0; iter < pieceCount; iter++) { newNumber = Random.Range (0, pieceCount); PieceScript parentToChildComp = pieces [newNumber].GetComponent<PieceScript> (); while( usedNumbers.Contains( newNumber ) || newNumber == iter || parentToChildComp.whoDoIControl == iter)//add impossible fix here. { newNumber = Random.Range( 0, pieceCount); parentToChildComp = pieces [newNumber].GetComponent<PieceScript> (); } PieceScript assignPieceChild = pieces [iter].GetComponent<PieceScript> (); assignPieceChild.whoDoIControl = newNumber; // this needs to be edited to an array whoDoIControl[iter] for multiple children I think. usedNumbers.Add( newNumber ); } cameraCenter = ((pieces[pieceCount - 1].transform.position - pieces[0].transform.position)) + pieces[0].transform.position; transform.position = new Vector3(cameraCenter.x, cameraCenter.y,-10); }
Read Entire Article