Question by
Impostor Studios · Apr 16, 2016 at 08:47 PM ·
gameobject
How do I switch characters?,How do I switch caracters? I have this code that works but I cant figure out how to make it work if I have more than 2 characters. Please help.
using UnityEngine; using System.Collections;
public class CubeSwitcher : MonoBehaviour {
GameObject LCube, TCube, UCube, ZCube,ZCube2;
int playerSelect;
// Use this for initialization
void Start () {
playerSelect = 1;
LCube = GameObject.Find("LCube");
TCube = GameObject.Find("TCube");
TCube.SetActive (false);
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.DownArrow))
{
if (playerSelect == 1) {
playerSelect = 2;
} else if (playerSelect == 2)
{
playerSelect = 1;
}
}
if (playerSelect == 1) {
LCube.SetActive (true);
TCube.SetActive (false);
} else if (playerSelect == 2)
{
LCube.SetActive (false);
TCube.SetActive (true);
}
}
}
Comment
Best Answer
Answer by Scribe · Apr 17, 2016 at 11:24 AM
You ought to look up some tutorials around using arrays and/or lists as when you have a large or unknown number of things to save that are related to each other, is prime use! Here's an example of how you might solve your problem:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CubeSwitcher : MonoBehaviour {
string[] cubePrefix; //array of prefixes to append to "cube" to lookup gameobject names
GameObject[] cubes; //the cubes that we find
int playerCount; //the number of cubes found
int playerSelect; //the current active cube
void Start () {
cubePrefix = new string[3]{"L", "T", "Z"};
List<GameObject> c = new List<GameObject>();
playerSelect = 0;
for(int i = 0; i < playerCount; i++){
GameObject go = GameObject.Find(cubePrefix[i] + "Cube");
if(go != null){ //if we didn't find the object, skip it!
if(c.Count == playerSelect){
go.SetActive(true); //if this cube is the currently selected one, activate!
}else{
go.SetActive(false); //else deactivate
}
c.Add(go); //then add it to our list and carry on
}
}
cubes = c.ToArray(); //make our list an array
playerCount = cubes.Length; //save the number of objects found
}
// Update is called once per frame
void Update(){
if (Input.GetKeyDown(KeyCode.DownArrow)){
playerSelect = (playerSelect+1)%playerCount;
// the '%' in 'a%b' returns the remainder after the division of a/b
//hence this moves through our objects cyclically
//(the last item goes back to the first item)
//look up modulo arithmetic for more info!
for(int i = 0; i < playerCount; i++){
cubes[i].SetActive(i == playerSelect); //set active if currently selected
}
}
}
}
hope that helps,
Scribe
Your answer
![](https://koobas.hobune.stream/wayback/20220612074953im_/https://answers.unity.com/themes/thub/images/avi.jpg)