- Home /
How can I access a component in a parent object?
Hello.
I'm raycasting on an object whom has a parent and I want to access a component on the parent, how do I do this?
this code:
void Update () {
Cylinder otherobject;
RaycastHit hit;
Vector3 angle0 = transform.TransformDirection(Vector3.up);
if (Physics.Raycast(transform.position, angle0, out hit, 1)){
otherobject = hit.collider.gameObject.transform.parent.GetComponent <script>().something();
}
}
How can I access a function on the script? the error I get: Cannot implicitly convert type void' to
Cylinder'
How can I fix this?
Thanks!
Answer by dmg0600 · Sep 19, 2014 at 11:13 AM
That error shows that the method "something()" is not returning anything as it is declarated like this:
public void something() {
//code
}
Just be sure that the method you are using from the parent returns a Cylinder.
The way you are accessing the component in the parent is right although I would just get it as follows:
if (Physics.Raycast(transform.position, angle0, out hit, 1))
{
otherobject = hit.transform.parent.GetComponent<script>().something();
}
But what I want is basically when the raycast hits the object I want the parent object to do something for example destroying itself, how can I accomplish this?
Just call the method without storing the return value in a variable. Like this:
void Update () {
RaycastHit hit;
Vector3 angle0 = transform.TransformDirection(Vector3.up);
if (Physics.Raycast(transform.position, angle0, out hit, 1))
{
hit.transform.parent.GetComponent<script>().something();
}
}
The problem was you were trying to store the return value of the method "something()" into your variable otherobject which wasn't posible as "something()" didn't return anything.
If this solves your problem please mark it as answered.
Right, sorry, I just editted my comment above. Now it should work.
Your answer
Follow this Question
Related Questions
Make a simple tree 1 Answer
How can I differentiate between colliding with an object or its child? 1 Answer
Raycasting from child weird behaviour 2 Answers
Instantiate as a child? 3 Answers
Raycast only returning parent object; need child hit 3 Answers