- Home /
make the object know its selected (C#)
So i have a targeting script. What code should i use to inform that an object is selected ? this is what i have so far..
using UnityEngine;
using System.Collections; using System.Collections.Generic;
public class targeting : MonoBehaviour { public List targets; public Transform selectedTarget;
private Transform myTransform;
// Use this for initialization
void Start () {
targets = new List<Transform>();
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));
});
}
//if we do not have an enemy targeted ywt, then find the clostest one and target him
//if we do have an enemy targeted, then get the next target
//if we have the last target in the list, then get then first target in the list
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;
}
DeselectTarget();
selectedTarget = targets[index];
}
SelectTarget();
}
private void SelectTarget() {
selectedTarget.renderer.material.color = Color.red;
}
private void DeselectTarget() {
selectedTarget.renderer.material.color = Color.white;
selectedTarget = null;
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.Tab)) {
TargetEnemy();
}
}
}
Its from BirgZerg..
how do i make it so when it selects an object, that object knows that its selected.
i want to create a quest system in which you need to select the people and then left click to make the dialogue apear for each object that can speek. Please Help!
Answer by Waz · Jul 07, 2011 at 04:07 AM
Either add a redundant Boolean in the target item type and set them from this script, or have the targets compare their gameObject with the current value of selectedTarget. Do all your Enemy objects have a script in common (say, Enemy.js)?If so, that's the place to put the redundant variable or to do the lookup.
what do you mean? where should i add it? im sorry im new to c# . Can you show me an example of how it should look?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How does Unity handle GameObject selection in the Scene View? 1 Answer
Character Selection 0 Answers
Best way for me to deselect something once it's selected? 0 Answers