- Home /
Having trouble using coroutines, making unity hang
Hello and thank you for reading this. I have some trouble running a coroutine in my rpg game. I'm still making the prototype(trying to make everything function on a basic level). What i've done so far,is make the player controlled units attack a target that you select by pressing a button, and then waiting for the user to actually target the unit to attack. I have limited experience using coroutines, so any input or explanation would be useful.The code for the targeting system is below:
void Update () {
if(Input.GetButtonDown("Fire1"))
{
TargetRay=Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast (TargetRay,out hit,100,enemymask)){
Target(hit.collider.gameObject);
Friendly=false;
// Debug.Log ("Enemy!");
}
else if(Physics.Raycast (TargetRay,out hit,100,playermask)){
Target(hit.collider.gameObject);
Friendly=true;
// Debug.Log("Player!");
}
}
}
public GameObject Target(GameObject target){
if(selectedTarget==null){
selectedTarget=target;
}
else{
Deselect();
selectedTarget=target;
}
selectedTarget.renderer.material.color=Color.red;
return selectedTarget;
}
public void Deselect(){
selectedTarget.renderer.material.color=Color.gray;
selectedTarget=null;
}
}
The code for the combat system is below:
void Update () {
if(Input.GetButtonDown("Attack")){
//Targeting.selectedTarget.renderer.material.color=Color.gray;
//Targeting.selectedTarget=null;
origin=TurnSystem.GetCurrentOrigin();
OriginStats=origin.GetComponent("Stats")as Stats;
Debug.Log ("Select a target to attack for "+OriginStats.Damage+"damage" );
StartCoroutine(Attack (origin));
}
}
public IEnumerator Attack(GameObject Go){
//Debug.Log ("Select a target to Attack");
if(Targeting.selectedTarget!=null){
Targeting.Deselect();
}
yield return StartCoroutine(WaitForTarget());
target=Targeting.selectedTarget;
TargetStats=target.GetComponent("Stats")as Stats;
TargetStats.HP=TargetStats.HP-OriginStats.Damage;
//Go.transform.position=target.transform.position; //should wait for attack animation to finish
// Go.transform.position=OriginalPosition;
OnAttackEnd();
}
public IEnumerator WaitForTarget(){
while(Targeting.selectedTarget==null){
if(Targeting.selectedTarget!=null && Targeting.Friendly==true){
Debug.Log("The target you selected is friendly.Please select an enemy target.");
Targeting.Deselect();
}
else if (Targeting.selectedTarget!=null && Targeting.Friendly==false){
Debug.Log ("Target is",Targeting.selectedTarget);
yield break;
}
}
yield return 0 ;
}
Thanks!
Your answer
Follow this Question
Related Questions
Coroutines not passing yield 1 Answer
Yield return inside a loop slowdown problem 2 Answers
WaitUntil doesn't work and the coroutine starts anyways 1 Answer
How to use Coroutines in C++/CLI? 1 Answer
Yielding in between functions... 2 Answers