0
votes

I have a simple script that should grab a GameObject's transform position and rotation then move the GameObject back to that position when it's hit by a Raycast. (Objects get moved around as the player bumps into them).

Its working fine for the objects that already have the script attached but when I apply the script to a new GameObject, it resets the transform's values to (0,0,0),(0,0,0) in the scene editor.

I'm sure there's a smarter way to do this.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TransformReset : MonoBehaviour
{
    private Transform LocalTransform;
    private Vector3 InitialPos;
    private Quaternion InitialRot;

    private Vector3 CurrentPos;
    private Quaternion CurrentRot;

    void Start()
    {
        InitialPos = transform.position;
        InitialRot = transform.rotation;       
    }

    public void Reset()
    {
        transform.position = InitialPos;
        transform.rotation = InitialRot;
        Debug.Log("resetting position of " + gameObject.name);
    }
}

that "public void Reset()" part is called by my raycasting script. But I think the problem is that its running in the scene editor before ever getting a useful "InitialPos" value.

Appreciate any help and advice.

1

1 Answers

6
votes

Reset is a MonoBehaviour Message that the engine calls under certain conditions. From the documentation, emphasis mine:

Reset is called when the user hits the Reset button in the Inspector's context menu or when adding the component the first time. This function is only called in editor mode. Reset is most commonly used to give good default values in the Inspector.

Basically, your naming of the method is colliding with built in behaviour it shouldn't have anything to do with. If you change the name of your method to something else, it should work fine:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TransformReset : MonoBehaviour
{
    private Transform LocalTransform;
    private Vector3 InitialPos;
    private Quaternion InitialRot;

    private Vector3 CurrentPos;
    private Quaternion CurrentRot;

    void Start()
    {
        InitialPos = transform.position;
        InitialRot = transform.rotation;       
    }

    public void ResetTransform()
    {
        transform.position = InitialPos;
        transform.rotation = InitialRot;
        Debug.Log("resetting position of " + gameObject.name);
    }
}

And then in the other class:

transformResetComponent.ResetTransform();