using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TriggerBool : MonoBehaviour {
public string gameObjectToReference;
public string scriptToReference;
public string boolToReference;
public string setBoolTo;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.name == "Player")
{
GameObject.Find(gameObjectToReference).GetComponent<scriptToReference>.boolToReference = setBoolTo;
}
}
}
This is the code I’ve got, but it cannot get the component of scriptToReference because it doesn’t exist yet. I wanted to use this code as a multipurpose script to be used in many places, where the character enters a trigger collider and it sets a bool of a given script. I would like to use this in many places in the game I’m making, instead of making a lot of custom one line scripts.
Sorry for any formatting issues, first time posting on this forum.
I think all you can do is this. (last example)
Instead of doing as HingeJoint
you can try as MonoBehaviour
Let me know if it works.
As silvematt says, it’s possible to call GetComponent(string nameOfType) instead of GetComponent(), though it’s not as efficient and you won’t be protected from typos.
But it looks like you’re also string to use a string to specify the field name of a variable you want to set. There’s no equivalent for that. There might possibly be something you can do involving reflection, but this is really the wrong approach.
The best way to do this is probably to use events. If you’ve ever used a Unity Button, you know how you can use the inspector to tell it to call a specific function on a specific component when the button is clicked? You can write your own class to do the same thing, something like this (untested):
using UnityEngine;
using UnityEngine.Events;
public class ReactToPlayerContact : MonoBehaviour {
public UnityEvent onPlayerContact;
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.name == "Player")
{
if (onPlayerContact != null) onPlayerContact();
}
}
}
Another way to do something like this in C# is with polymorphism. Define an interface or base class that contains the bool you want to modify (or a function that accepts a bool argument), and then make all the classes you want to reference from this script implement that interface or inherit from that base class. (For convenience, you probably want to use a base class that derives from MonoBehaviour, so that you get all the Unity editor built-in recognition of MonoBehaviours.)
Then ideally you skip the “find” and give this class a direct reference to the component you are interested in by dragging it into a public field in the Unity inspector. But if you really need to find an object by name for some reason you can keep doing that part.
1 Like