- Home /
How to get Scripts attached GameObject from within a Struct declared in the Class
Example layout:
public class SomeClass : MonoBehaviour {
private struct SomeData
{
private Transform obj;
SomeData(Transform t)
{
if (t.parent == transform) <------ Cannot access "transform"
obj = t;
else
// throw an error
}
}
}
I want to access the Transform that this Script is attached to as I need to make sure that the Transform that's passed into the Struct's constructor is a Child of the Transform that the Script is attached to (hope that makes sense).
Note: I've tried adding a public Property to the Class, but the Struct still has no access to it:
// within the Class specified above
public Transform GetTransform { get { return transform; } }
Any help is very much appreciated.
Answer by fafase · Dec 11, 2015 at 01:06 PM
I won't discuss the design at first but will only fix the issue. The struct is no MonoBehaviour so it does not contain the transform reference, you need to pass it as well.
public class SomeClass : MonoBehaviour {
private struct SomeData
{
private Transform obj;
SomeData(Transform transform, Transform t)<------ Pass "transform"
{
if (t.parent == transform)
obj = t;
else
// throw an error
}
}
}
Now about the design, it would easier to make the check out of the constructor so you only create the struct if the check is ok.
I was trying to not have to pass it as a variable, but I guess if that's the only way then I'l do it like that. And since the struct's private to the class I guess it's not a big deal if it's a parameter anyway..
Thanks for the response.
Your answer
Follow this Question
Related Questions
Finding class where current GameObject is assigned to as a var 1 Answer
Best way to calculate sum of custom object holding numbers and returning sum as that object instance 0 Answers
Is it possible to Change mesh also multi materials by a button or a key 0 Answers
Accessing another script from a class 3 Answers
How would I access a Class Variable from another script? 1 Answer