- Home /
Assigning variables to GameObjects
I am making a script to call variables from the object which hits the targets to calculate force. But, I was wondering if there was a simple way to make a private variable to that GameObject and later to be able to access it like you can do with transform.
In tranform you can do
terrain.transform or this.transform I want to be able to access a variable like that be able to do. var bulletWeight : float = GameObject.Find("Bullet").weight; bullet.mass etc.
Is there a way to do this? Without making a script to assign the value and then accessing that script value and calling it from there? I rather not do it this way unless I have too.
quick note. I wouldn't ever use GameObject.Find("") if I were you. Especially for objects like bullets which quickly spawn and are destroyed. $$anonymous$$ake sure you keep references to objects like bullets. Or even use a circular queue of say 10 blank bullet references.
Next Beat, how would you do this? I am still new to UnityScript and trying to learn so I have $$anonymous$$imal knowledge of this.
ok i will try to explain with pseudo code:
class CBullet { Vector3 startPos; Vector3 endPos; }
// In your script you wish to use bullets in:
CBullet[] bullets[10]; // 10 = max bullets used by this transform
int queuePosBegin = 0;
int queuePosEnd = 0;
public fire() { bullets[++queuePosEnd].startPos = gun$$anonymous$$uzzlePos; bullets[queuePosEnd].endPos = gun$$anonymous$$uzzlePos+(gun$$anonymous$$uzzle.Forward * someConstant); }
OnBulletHit() { ++queuePosBegin; }
Answer by Piflik · Jan 02, 2013 at 10:41 PM
You cannot access private variables directly from other scripts at all. You would need getter/setter functions...
Public variables can be accessed by:
gameObject.GetComponent(ScriptName).VariableName; //UnityScript
//or
gameObject.GetComponent<ScriptName>().VariableName; //C#
Also, GameObject.Find() should only ever be called in Start() or Awake(). Don't call it repeatedly, since it is quite expensive.
Answer by jogo13 · Jan 02, 2013 at 10:44 PM
You'll have to do it via attached script classes (which can be attached as 'components.') Even the basic Gameobject is class that is a collection of other classes and structs (such as transform.)
Simple class example (c#)
using UnityEngine;
using System.Collections;
public class bullet : MonoBehaviour {
float weight;
float speed;
}