- Home /
Function executes only on 1 object
Hi,
I have two types of objects in my scene. GameObject[] Blockers and GameObject[] Meshes. If there is a Blocker object right on top of Mesh object I want Mesh object to change material. Blockers objects are moveable, so I want to execute this in Update().
But this function only works in Start() and in Update() only works on 1 object. Even though I checked, and for 2 Blockers, contition "occupied" returns true for 2 Meshes. But function SetMaterialsHere() executes only on 1 object.
So first question: why is that?
And second: is it a good way to change materials? Do I realy want this code to run every frame? Wont this slow down my game?
void Action(GameObject[] Blockers, GameObject[] Meshes)
{
foreach (GameObject b in Blockers)
{
foreach (GameObject m in Meshes)
{
Vector3 positionToCheck = b.transform.position + Vector3.down;
bool occupied = m.transform.position == positionToCheck;
if (occupied)
{
SetMaterialsHere();
}
}
}
}
if occupied is true setmaterialshere has to be executed twice, whats the setmaterialshere method? have you logged in and out of the if something for knowing how many times is true?
Answer by JJ_FX · Mar 15, 2019 at 01:28 PM
Ok I have found the problem. This was not the whole code. Thats whats going on:
if (occupied)
{
SetMaterialsHere(Material X);
} else {
SetMaterialsHere(Material Y);
}
So besically my material is set to Material X, but then when iterating over next Blocker object is overwrites the material back to Material Y...
So the proble is foreach inside foreach.... How to deal with that?
set all the materials to Y first (outside those foreach) and inside the foreach only assign x if its occupied