Can't change color of sprites in unity
- by Aceleeon
I would like to create a script that targets a 2d sprite "enemy" and changes their color to red (slightly opaque red if possible) when you hit tab.
I have this code from a 3d tutorial hoping the transition would work. But it does not. I only get the script to cycle the enemy tags but never changes the color of the sprite.
I have the code below
I'm very new to coding, and any help would be FANTASTIC! HELP! hahah.
TL;DR Cant get 3d color targeting to work for 2D. Check out the c#code below
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Targetting : MonoBehaviour {
public List targets;
public Transform selectedTarget;
private Transform myTransform;
// Use this for initialization
void Start () {
targets = new List();
selectedTarget = null;
myTransform = transform;
AddAllEnemies();
}
public void AddAllEnemies()
{
GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");
foreach(GameObject enemy in go)
AddTarget(enemy.transform);
}
public void AddTarget(Transform enemy)
{
targets.Add(enemy);
}
private void SortTargetsByDistance()
{
targets.Sort(delegate(Transform t1,Transform t2) {
return Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position));
});
}
private void TargetEnemy()
{
if(selectedTarget == null)
{
SortTargetsByDistance();
selectedTarget = targets[0];
}
else
{
int index = targets.IndexOf(selectedTarget);
if(index < targets.Count -1)
{
index++;
}
else
{
index = 0;
}
selectedTarget = targets[index];
}
}
private void SelectTarget()
{
selectedTarget.GetComponent().color = Color.red;
}
private void DeselectTarget()
{
selectedTarget.GetComponent().color = Color.blue;
selectedTarget = null;
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Tab))
{
TargetEnemy();
}
}
}