Trouble combining two simple scripts
Hello :)
When I hit a object tagged "RemovableObject", I want the object thats been hit to be deactivated and be activated again after 10 seconds. That part works with this script:
using UnityEngine;
using System.Collections;
public class RemovableObject : MonoBehaviour
{
IEnumerator OnCollisionEnter (Collision col)
{
if(col.gameObject.tag == "RemovableObject")
{
col.gameObject.SetActive (false);
yield return new WaitForSeconds (10);
{
col.gameObject.SetActive (true);
}
}
}
Now I want to make the object blink before appearing again, so I found this script:
void Start ()
{
StartCoroutine(DoBlinks(3f, 0.2f));
}
IEnumerator DoBlinks(float duration, float blinkTime)
{
while (duration > 0f)
{
duration -= Time.deltaTime;
//toggle renderer
GetComponent<Renderer>().enabled = !GetComponent<Renderer>().enabled;
//wait for a bit
yield return new WaitForSeconds(blinkTime);
}
//make sure renderer is enabled when we exit
GetComponent<Renderer>().enabled = true;
col.gameObject.SetActive (true);
}
}
I am not able to combine the two scripts without getting any errors :/ Any help would really be appreciated!
Answer by Taxen0 · Feb 05, 2016 at 07:54 PM
I haven't actually tried to do something like this from the OnCollisionEnter method before, but give this a try and tell me if you run into any issues. (untested code)
using UnityEngine;
using System.Collections;
public class Bullet: MonoBehaviour {
IEnumerator OnCollisionEnter (Collision col)
{
if(col.gameObject.tag == "RemovableObject")
{
col.gameObject.SetActive (false);
yield return StartCoroutine(DoBlinks(3f, 0.2f, col.gameObject));
col.gameObject.SetActive (true);
}
}
IEnumerator DoBlinks(float duration, float blinkTime, GameObject target)
{
while (duration > 0f)
{
duration -= Time.deltaTime;
//toggle renderer
target.GetComponent<Renderer>().enabled = !target.GetComponent<Renderer>().enabled;
//wait for a bit
yield return new WaitForSeconds(blinkTime);
}
//make sure renderer is enabled when we exit
target.GetComponent<Renderer>().enabled = true;
target.gameObject.SetActive (true);
}
}
It returns an error on line 31: The name `col' does not exist in the current context..
Never $$anonymous$$d, It works, I just removed line 31. But I had this script attached to the bullet and not the object I wanted to blink. Thanks
Wait no, this is wrong! The gameObject is not being disabled, the bullet is! :P It has to be the other way around. This script has to be attached to the BulletPrefab and deactivate what it hits.
I see that i made some mistakes, I have updated the script so make another go. and yes, this is meant to be on the bullet (but should deactivate the correct target now)