- Home /
Access object from script problem.
I have found many suggestions using google, on how to access the object which your script is attached to, but common for all of them are: They do not work! Because it involves a ":" in the initialization, which Unity won't accept.
My question(s) are:
1a) Could this be a product of failure, due to the fact I use the free version?
1b) ...if not, can you access an object which the script is attached to, without using ":"?
Your question does not make much sense. For any script, you can use 'gameObject' (small 'g') to access the game object the script is attached to. Please post your code to get a more accurate answer.
Yeah I have tried that too (gameObject, according to examples), but it doesn't work either. The question makes perfect sense, as the problem is written clearly. Not knowing the context because you know too little of the issue ...yes I admit that might give problems, but I can only redirect you to the various examples I found using google, as it is their code I used.
However I can tell you I want to access the objects X, Y and Z, through the script, that it is attached to.
Answer by Murkas · Jan 26, 2014 at 04:32 PM
Just like this (As an example):
using UnityEngine;
using System.Collections;
public class YourScript : MonoBehaviour
{
void Start(){
gameObject.transform.position=new Vector3(0.2f,0.5f,0.3f);
}
void Update(){
float x = gameObject.transform.position.x;
//do whatever you want with this x
//since we can't change x directly, we have to do a workaround
Vector3 LastPos = gameObject.transform.position;
LastPos.x=x;
gameObject.transform.position=LastPos;
}
}
I like your answer, but you set the variables, I need to retrieve them, and I did try gameObject.transform.x + variations of it, to no success.
Okay, what exactly do you want to do?
Read the single variables (x,y,z) - Write the single variables (x,y,z) - In/Decrease the single variables (x,y,z)
I need to read them to assign them to other variables, then process those variables with a math-function(non-code), then assign that product back to the original variables.
Thank you very much $$anonymous$$urkas, gonna try it out.
Just tried it out, Unity says it can't find gameObject. I really hope this is because I got the free version. UPDATE: Unity even gives errors NOW, for the script that comes with it, saying it can't find gameObject. This is getting sick, excuse me for my language.