how to change object's B color when object A is in range? 2D
I have an enemy AI object that randomly patrols a top down 2d maze(object B) and within this maze are tiles(multiple objects of A). I'm having trouble figuring out a way to change any tiles that is within close distance to the enemy object B. Here is my code:
public Transform blocks;
private void Update()
{
blocks = GameObject.FindGameObjectWithTag("Breakable_Block").transform;
if (Vector2.Distance(transform.position, blocks.position) < 10)
{
blocks.GetComponent<Renderer>().material.color = Color.green;
}
}
Thanks in advance!
Answer by tormentoarmagedoom · Jul 17, 2018 at 06:44 AM
Good day.
Look at your code:
GameObject.FindGameObjectWithTag("Breakable_Block") is a single object
you can go find all blocks, and check all of them if...
public Transform[] blocks;
private void Update()
{
blocks = GameObject.FindGameObjectsWithTag("Breakable_Block").transform;
foreach (Transform OneBlock in blocks)
{
if (Vector2.Distance(transform.position, OneBlock.position) < 10)
{
OneBlock.GetComponent<Renderer>().material.color = Color.green;
}
}
}
Now, you check all the blocks positions, 1 by 1, and thatones thar are closer than 10, will change its color.
Bye!
hello and thank you for answering my question. I've applied your code but I get this error.
Severity Code Description Project File Line Suppression State Error CS1061 'GameObject[]' does not contain a definition for 'transform' and no extension method 'transform' accepting a first argument of type 'GameObject[]' could be found (are you missing a using directive or an assembly reference?) Assembly-CSharp C:\Users\mende\Desktop\Unity Projects\Invisible$$anonymous$$aze\Assets\Scripts\Enemy\EnemyHotSpot.cs 11 Active
Your answer
Follow this Question
Related Questions
Javascript 2D change color of spriteRenderer through script 1 Answer
Help Change Color of Object on Collide 1 Answer
Shift a Sprite's color palette? 0 Answers
Why is the tilemap color change messed up? 0 Answers
How to make RANDOM COLOR on shader 1 Answer