How to set a line of code to be a variable
I have a line that of code that i use over and over several times in different ways
GameObject.Find("colorswitchred (" + id.ToString() + ")").transform.GetComponent<Main>().state
such as:
if (GameObject.Find("colorswitchred (" + id.ToString() + ")").transform.GetComponent<Main>().state < 3)
{
GameObject.Find("colorswitchred (" + id.ToString() + ")").transform.GetComponent<Main>().state ++;
}
else
{
GameObject.Find("colorswitchred (" + id.ToString() + ")").transform.GetComponent<Main>().state = 1;
}
Is there a way I can set a string[] or something to be this line of code, that way I can just do like
if (tile < 3)
{
tile ++;
}
else
{
tile = 1;
}
Comment
Answer by TreyH · Nov 10, 2016 at 04:08 PM
Also known as a "function":
private Main FindSwitch( int id)
{
// Return the component following this sort of search (I'm assuming this is an integer)
return GameObject.Find("colorswitchred (" + id.ToString() + ")").transform.GetComponent<Main>();
}
Then your code might become:
Main switchMain = FindSwitch(id:);
if (switchMain.state < 3)
{
switchMain.state ++;
}
else
{
switchMain.state = 1;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612100426im_/https://answers.unity.com/themes/thub/images/avi.jpg)