How to deal with repetetive code?
Hello guys!
I have a fairly "simple" question. Often I find myself writing very repetetive code, with tons of "if" statements. I'd just like to know how I am actually supposed to deal with this, and what way is the correct way to do it.
Example on repetetive code:
if (popUpPosition1.transform.childCount >= 2)
popUpPosition1.transform.GetChild(0).transform.SetParent(popUpPosition2.transform, false);
if (popUpPosition2.transform.childCount >= 2)
popUpPosition2.transform.GetChild(0).transform.SetParent(popUpPosition3.transform, false);
if (popUpPosition3.transform.childCount >= 2)
popUpPosition3.transform.GetChild(0).transform.SetParent(popUpPosition4.transform, false);
if (popUpPosition4.transform.childCount >= 2)
popUpPosition4.transform.GetChild(0).transform.SetParent(popUpPosition5.transform, false);
if (popUpPosition5.transform.childCount >= 2)
popUpPosition5.transform.GetChild(0).transform.SetParent(popUpPosition6.transform, false);
if (popUpPosition6.transform.childCount >= 2)
Destroy(popUpPosition6.transform.GetChild(0));
I'd just like to know what to use. A friend of mine told me something about having to learn "objects" but I am not entirely sure what he meant by that.
Thanks in advance!
Answer by fafase · Aug 25, 2015 at 03:01 PM
public Transform[] popUpPositions; // Drag all pop up in there
then
for(int i = 0; i < popUpPositions.Length; i++){
if(i == popUpPositions.Length - 1){
Destroy( popUpPositions[i].gameObject);
continue;
}
popUpPositions[i].GetChild(0).SetParent(popUpPositions[i+1], false);
}
Answer by Landern · Aug 25, 2015 at 03:02 PM
Well you have some patterns you can using to optimize your code.
It appears each popUpPosition# does the same logic, it would also seem like each is the same type(GameObject or RigidBody perhaps?).
You can start by putting all your popUpPosition objects into the same bucket or collection.
If you're using the Unity Inspector to set each popUpPosition then exposing a public List type should do
// Normal Code, Class definition, usings, assuming c#
[System.Serializable]
public List<GameObject> popUpPositions;
public void SomeMethod()
{
// we want to iterate over positions 1 through 5 and give 6 it's own special logic since it differs from the others in logic. This is reason for Count - 1
for(int i = 0; i < popUpPositions.Count - 1; i++)
{
if (popUpPosition[i].transform.childCount >= 2)
popUpPosition[i].transform.GetChild(0).transform.SetParent(popUpPosition[i+1].transform, false);
}
// Get the index of the last item in the list, the list is zero based, the count is 1 base, removing one from count allows the last index in the collection.
if(popUpPosition[popUpPosition.Count-1].transform.childCount >= 2)
Destroy(popUpPosition[popUpPosition.Count - 1].transform.GetChild(0));
}