Hi ! ^^
I have a script and I want to change some variables inside this script when the player click on an another game object which is not attached to this script. I want also change some variables in this script when an another object collides with an object with a specific tag. I think my two questions are linked ^^
I know the command OnMouseDown and CompareTag but I don’t know how to tell in my script that the variables will change when the mouse click on an another object or when another object collides with an object taged.
Thanks for your answers ! ^^
Thanks for your answer but I don’t understand very well how it works ^^’
Can you give me an example with a script attached to the GameObject n°1 which contains the variable Example and when the mouse click on the GameObject n°2, the variable Example changes to 1 ? ^^
getComponent to get the script so if the script is on gameobject1
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class randomScript : MonoBehaviour {
NameOfScriptYouWantToEffect nameYouUseInYourScript
// Use this for initialization
void Start () {
nameYouUseInYourScript = GameObject.Find("gameobject1").GetComponent<NameOfScriptYouWantToEffect>();
}
// Update is called once per frame
void Update () {
if (nameYouUseInYourScript.getData == true) {
//do random crap here//
}
}
}
so in the other script you have something like:
public bool getData {
get {
return randomBool;
}
}
There are many ways to get hold on a script inside of another script , For example you can make a variable to save it and give it any name you like ,you just need to make the type of the variable is the same as the script name, lets say we have a scrip called “ScriptOne.cs” to acces it from another script we would use the following code:
public ScriptOne variableName;
we are saving the script in the variable “variableName”, lets imagine the script has a public variable float called “floatVariable” to acces it and give it a value, we would do the following:
variableName.floatVariable = 3.14f;
other ways are sometimes better like
FindObjectOfType<ScriptOne> ().floatVariable = 3.14f;
You can also use GetComponent
Well thats for referencing the script
now tochange a value from another script when you collide you could use the following methods
void OnCollisionEnter(Collision info)
{
if(info.gameObject.CompareTag("MyTag"))
{
FindObjectOfType<ScriptOne> ().floatVariable = 3.14f;
}
}
OR
void OnTriggerEnter(Collider info)
{
if(info.gameObject.CompareTag("MyTag"))
{
FindObjectOfType<ScriptOne> ().floatVariable = 3.14f;
}
}
To activate something when you press it you need other methods
like OnMouseDown()
void OnMouseDown()
{
FindObjectOfType<ScriptOne> ().floatVariable = 3.14f;
}
or maybe use some raycasts .