Hi fellow Programmers, I cant get my c# script to work. its suposed to lift up a few Objects that I have put around my game-world. how can I make it work?
using System.Collections.Generic;
using UnityEngine;
public class PropControl : MonoBehaviour
{
//Variablen
public GameObject Object1;
public GameObject Object2;
public GameObject Object3;
public GameObject O1;
public GameObject O2;
public GameObject O3;
// Start is called before the first frame update
void Start()
{
O1.SetActive (true);
O2.SetActive (true);
O3.SetActive (true);
Object1.SetActive (false);
Object2.SetActive (false);
Object3.SetActive (false);
}
// Update is called once per frame
void OnTriggerStay(Collider other)
{
Debug.Log (“LOG”);
if (other.name == “Weapon1”)
Object1.SetActive (true);
Object2.SetActive (false);
Object3.SetActive (false);
if (other.name == “Weapon2”)
Object2.SetActive (true);
Object1.SetActive (false);
Object3.SetActive (false);
if (other.name == “Knife”)
Object3.SetActive (true);
Object1.SetActive (false);
Object2.SetActive (false);
}
}[/code]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PropControl : MonoBehaviour
{
//Variablen
public GameObject Object1;
public GameObject Object2;
public GameObject Object3;
// Start is called before the first frame update
void Start()
{
Object1.SetActive (false);
Object2.SetActive (false);
Object3.SetActive (false);
}
// Update is called once per frame
void OnTriggerStay(Collider other)
{
Debug.Log ("LOG");
if (other.name == "Weapon1")
Object1.SetActive (true);
Object2.SetActive (false);
Object3.SetActive (false);
if (other.name == "Weapon2")
Object2.SetActive (true);
Object1.SetActive (false);
Object3.SetActive (false);
if (other.name == "Knife")
Object3.SetActive (true);
Object1.SetActive (false);
Object2.SetActive (false);
}
}
You need to wrap up the code that is being executed with the if statements with { and } symbols. I also don’t recommend re-ordering the methods within them because at a glance it’s not immediately obvious why you did it and that can lead to code that is more difficult to debug.
Even though this overall approach is not great, your 3 if-statemens could be removed completely since you set the active state of all your objects in each case. You can simply do
When this code runs and the name iw “Weapon1”, only the first object will be activated and all the others would be deactivated because the boolean expression in the other cases is false.
Though your code does not really pick something up but switches the active weapon depending on what object you collide with. So i’m not really sure if what your script actually does what it should do. If you just wanted to switch the weapon when you collide with the corresponding object in your world, then yes, that’s what those 3 lines would do.