- Home /
how to make one script change a variable in another scipt
I want this script to change a variable in another script. The variable is called boxamount, in the script called Placegadget. this is what i have tried, but it won't worke.
using UnityEngine; using System.Collections;
public class Pickupgadget : MonoBehaviour {
void Update () {
if (Input.GetKeyDown(KeyCode.E))
{
Placegadget placegadget = GetComponent<Placegadget>();
placegadget.transform.SendMessage("plus",SendMessageOptions.DontRequireReceiver);
Vector3 fwd = transform.TransformDirection(Vector3.forward);
RaycastHit hit;
if (Physics.Raycast(transform.position, fwd, out hit, 1.5f))
{
Debug.DrawRay(transform.position, fwd, Color.green);
hit.transform.SendMessage("PickMeUp",SendMessageOptions.DontRequireReceiver);
}
}
} }
Answer by Berenger · Feb 06, 2012 at 03:10 PM
I don't see where is the variable you're trying to change, so I'll stay generic :
To access a variable of an object, you an instance and the right to access it (=> public/protected/private, to keep it simple). Make sure your boxamount is public.
Also, I see your accessing the component Placegadget from the same object, to SendAMessage. You don't need to do that to a function from it. It wored, but you didn't take the shortest way (Get the component, get it's transform, send a message to every components of that object, the first component pick it up, execute) when you just need to call SendMessage from the script you wrote.
Answer by MrLolEthan · Nov 02, 2012 at 05:56 PM
Here is an example how:
var objectWithTheScript : GameObject;
var theScript;
function Start() {
theScript = objectWithTheScript.GetComponent("The Scripts Name");
}
function Update() {
theScript.variableInTheScript = (whatever);
}
Now you can get much more complicated with that but that's it really!
Your answer
Follow this Question
Related Questions
GetComponent keeps returning null 3 Answers
Performance issues with SendMessage in FixedUpdate using Raycast 0 Answers
Why don't my send messages work? 2 Answers
Distribute terrain in zones 3 Answers
accesing scripts throu raycasthit 1 Answer