transform.parent for individual object
Hello, I have a prefab that spawning in the scene with a rigid body sleeper script on the child. But When I run this code it affects all my prefabs in the scene. I want to affect only its local parent. any suggestions?
using System.Collections;
using UnityEngine;
public class RigidSleeper : MonoBehaviour
{
private Rigidbody rbGO;
public float timer = 5 ;
bool setgo = true;
public float Yforce = 1;
private void Start()
{
rbGO = transform.parent.parent.parent.GetComponent<Rigidbody>();
}
void FixedUpdate()
{
if (Input.GetMouseButtonDown(0))
setgo = false;
if (setgo==true)
{
rbGO.AddForce(0, Yforce, 0);
}
else if (setgo==false)
{
rbGO = transform.parent.parent.parent.GetComponent<Rigidbody>();
rbGO.Sleep();
if (Input.GetMouseButtonUp(0))
StartCoroutine(coroutine());
}
IEnumerator coroutine()
{
if(setgo==false)
{
yield return new WaitForSeconds(timer);
setgo = true;
}
}
}
}
Answer by streeetwalker · Mar 24, 2020 at 07:20 AM
@cinemator, Well, your situation is more complex than you let on! If all you had was one parent and a child, then why does your code do:
transform.parent.parent.parent.GetComponent<Rigidbody>() ?
It looks like you are climbing the hierarchy all the way back up to some great-grandparent. If all you prefabs share a common parent, there is no "local" parent.
Perhaps what you mean to do is just:
transform.parent.GetComponent<Rigidbody>() ?
Answer by cinemator · Mar 24, 2020 at 10:11 AM
I wrote the code like that because my objects is the actually grandson of its parent.
Where do I have to look for to act all prefabs differently from their childs
@cinemator, Setting properties on one instance of a prefab or any of it's children won't affect another instance of the same prefab - the only way that happens is if you are either modify the prefab itself and not an instance; Or If you have instantiated two prefabs and then made them children of some existing object. Then, for example, applying motion to that new parent will make both prefab instances move.
We cannot tell in your script what is going on without seeing what your set up and other scripts look like.
OK, You clarify that you're acting on a grandson, but code looks like your climbing back up to a great-grandparent.
I think:
transform.child.grandchild.great-grandchild
and in reverse:
transform.parent.grandparent.great-grandparent.
so it looks like either you're climbing back too far, or you aren't describing the relationship to match your code.
(A prefab is essentially a template. I don't know, but maybe if you try to climb too far back out of a prefab instance, you do actually modify the prefab template? That's a theory that should be tested...!)
Your answer
Follow this Question
Related Questions
Velocity of parent local to child 1 Answer
How to set cursor as a parent 0 Answers
setParent. what am i doing wrong? 0 Answers
what object does the parent child code go on? 1 Answer
Drag, Drop, and Attach 0 Answers