I am building an instructional game for my students. I have 3 sample objects (Sample1, Sample2, Sample3) I need a script that turns two objects labeled Light on when Sample3 is in direct contact with GameObject TestBase. I have written the following code but this is new to me and nothing is happening. I can write the code to flip the light with space bar but not with the collision:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class on : MonoBehaviour
{
public Light myLight;
void OnCollisionEnter(Collision col)
{
if (col.gameObject.name == âSample3â)
{
myLight.enabled = true;
}
else
{
myLight.enabled = false;
}
}
}
Use code tags.
Collisions callbacks have to be triggered, with a keypress you can fire a method directly but Collisions happen between two colliders with at least one non-static and having a Rigidbody component. Itâs more involved than just âpress a button and poofâ.
1 Like
Thanks for the advice. I got the lights to turn on when only sample3 interacts now (yay) but the last step is for them to turn back off when contact is broken. My code is below for reference:
public class on : MonoBehaviour
{
public Light Light1, Light2;
void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == âsilverâ)
{
Light1.enabled = false;
Light2.enabled = false;
}
else
{
Light1.enabled = true;
Light2.enabled = true;
}
}
}
Posting code nicely on the forums, explained here: Using code tags properly - Unity Engine - Unity Discussions
It sounds as though youâre looking for OnTriggerExit.
1 Like
Thanks! That does look notably less disgusting, and now it works!!! Thank you, code below in case it helps anyone else.
public class on : MonoBehaviour
{
public Light Light1, Light2;
void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "silver")
{
Light1.enabled = false;
Light2.enabled = false;
}
else
{
Light1.enabled = true;
Light2.enabled = true;
}
}
void OnTriggerExit(Collider col)
{
if (col.gameObject.tag == "silver")
{
Light1.enabled = true;
Light2.enabled = true;
}
else
{
Light1.enabled = false;
Light2.enabled = false;
}
}
}
Small tip for checking tags: use â.gameObject.CompareTag(âTagNameHereâ)â.
glad itâs working for ya.
1 Like
using UnityEngine;
using System.Collections;
public class TriggerEvent : MonoBehaviour {
public GameObject lightBulb =null;
void OnTriggerEnter(Collider other ){
if (other.name == âplayerâ) {
lightBulb.SetActive (true);
}
}
void OnTriggerExit( Collider other){
if (other.name == âplayerâ) {
lightBulb.SetActive(false);
}
}
}
âŚ
light donât turn on and off with collision of two object whats my fault see my code iâm currently using unity 5 a lot of error iâm facing in this version