- Home /
set another scripts variable
Hi I'm just wondering how would I change a scripts variable from another script?
for example:
script1
var target : GameObject;
script2
var victim : GameObject;
how do I set the victim game object to the same game object as script1's target?
You asked this exact same question yesterday: http://answers.unity3d.com/questions/236939/setting-a-variable-to-a-variable-from-another-scri.html ...
Answer by GuyTidhar · Apr 09, 2012 at 07:32 AM
script1
var target : GameObject;
function InitProjectile()
{
var newProjectile : Projectile = Instantiate(porjectilePrefab,position,rotation);
var otherScript : newProjectile.GetComponenet.<script2>();
target = otherScript.victim;
}
you should of course update porjectilePrefab, position and rotation to the settings you are using...
this works but say im instantiating script2's object and i cant get script1's object so can I do this using script1 to set script2's object?
You can certainly change the scripts and have the Find() function running on script1 to look for script2! I can edit this one if you'd like...
if you are instantiating script2 after script1, why can't you get script1?
because its a tower defence games and there will be multiple turrets which have script1 so I cant find the right one.
Can you have all these GameObject representing the turrets under one GameObject parent? (something you should do in any case...)?
Answer by DJSwiti · Apr 09, 2012 at 08:58 AM
This is C#. I don't know how to convert a var from JS to something else in C#.. So i converted it in string. I may say wrong
Script 1 :
using UnityEngine;
using System.Collections;
public class script_one : MonoBehaviour {
static string target = GameObject;
}
And script 2 :
using UnityEngine;
using System.Collections;
public class script_two : MonoBehaviour {
void Update(){
if(.......){
script_one.target = ...;
}
}
}
If you can't modify the string target, that is because you must put it in public static string
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Variable in Inspector 1 Answer
Problems assigning transforms on another script during Start(). 2 Answers
Can't access Depth of Field? 2 Answers
2 small questions about scripting 1 Answer