I am using some scripts i downloaded off of the asset store for npc navigation. the scripts are easiest to use if they have a gameobject as a target to move to. id like to use this to make wandering animal npcs so i want an object assotiated with the parent animal but i want that object to stay stationary with comparison to the world and have the animal move towards this object and reach it then ill make a script to pick a new location. I would basically like to know if a child can be stationary and still allow the parent to move freely.
So you want the target gameobject to be a child of the moving animal gameobject ? That is going to complicate a lot of things for you. As a general rule, whenever you want a child gameobject to be stationary while the parent moves around it is almost always no point in having the child gameobject be parented to the moving object at all.
I recommend you to instead put both the animal and the target gameobject into another parent gameobject, that way you have them both organized and you do not have to apply some complicated movement code to the target to make it stationary.
While Its not usually recommended to do this (because it makes basically no sense in the majority of situations), it is indeed possible to not move a child with its parent, here is the code for the script I did. Just drag and drop it on the GameObject that you don’t want to move with its parent:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteAlways]
public class DontMoveWithParent : MonoBehaviour
{
Vector3 savedPosition;
[Tooltip("When DontMoveWithParent is on, Ctrl+Z doesn't work for movement changes on this GameObject.")]
public bool dontMoveWithParent = true;
bool lastDontMoveWithParent = true;
Vector3 parentLastPos;
private void Update()
{
if (transform.hasChanged && !transform.parent.hasChanged && savedPosition != transform.position)
{
savedPosition = transform.position;
transform.hasChanged = false;
}
if (!lastDontMoveWithParent && dontMoveWithParent)
savedPosition = transform.position;
lastDontMoveWithParent = dontMoveWithParent;
}
private void LateUpdate()
{
if (dontMoveWithParent)
{
if (savedPosition == Vector3.zero)
{
savedPosition = transform.position;
}
if (transform.parent.hasChanged)
{
transform.position = savedPosition;
transform.parent.hasChanged = false;
}
}
}
}