- Home /
Changing array materials on collision (c#)
Hi all, I am having a bit of trouble getting individual objects in an array to change their material on collision. The problem I am having is that this happens across the array and not just to specific blocks. The first collision works correctly, but if i then collide with an un-hit block, its material skips to the secondHit material or thirdHit material (if 2 different blocks have been hit previously).
As you can see i am also changing mass on collision, this seems to be working fine, which just adds to my confusion.
How can i get the individual blocks in the array to hold their own hit value? I thought using a foreach loop would fix this.
any help would be brilliant, thanks in advance! A.
public Material firstHit;
public Material secondHit;
public Material thirdHit;
public static int hitNumber = 0;
void OnCollisionEnter (Collision collision)
{
foreach (GameObject block in BlockCount.blocks) {
if (collision.gameObject == block) {
block.rigidbody.mass = block.rigidbody.mass / 2;
hitNumber++;
print(hitNumber);
if (hitNumber == 1) {
block.renderer.material = firstHit;
}
if (hitNumber == 2) {
block.renderer.material = secondHit;
}
if (hitNumber == 3) {
block.renderer.material = thirdHit;
hitNumber = 0;
}
}
}
}
Answer by DaveA · Mar 29, 2012 at 08:42 PM
You should make one block with this script that works, then make it a Prefab, then use that Prefab for all the rest of the blocks. Then they'll all have their own copy of the script with their own hit counts etc.
Your answer
![](https://koobas.hobune.stream/wayback/20220613065710im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
if collision.gameObject.tag == any of the elements in the array... 0 Answers
Transport unknown amout of objects with GameObject array 0 Answers
AudioClip.SetData not working 2 Answers
Array copy 2 Answers
Wrong object always Instantiated 1 Answer