3
\$\begingroup\$

I'm wondering if there is a way to have an Object when duplicated in the editor assign a GameObject variable to the newly duplicated version of itself. Is there an option in Unity or do I have to code it out.

So I would like it to follow these steps:

  1. So I would have the old GameObject with the variable named "nextStop" with nothing assigned to it.
  2. Then I duplicate said object and the older object's variable is assigned to the newly duplicated object.
  3. Done.

enter image description here

I'm doing this for a rail editor to make it easier to create new rails to follow.

enter image description here

I would like not to have to assign to each and every Object it will make things so much easier to explain for others to use. "Just duplicate these objects."

And in case you need it and Unity doesn't already have an option built in here's my code for the track.

using UnityEngine;
using System.Collections;

public class Rails : MonoBehaviour {

    public GameObject nextStop;
    LineRenderer myLine;
    public bool endLevel = false;
    public Train myShip;
    void OnDrawGizmos()
    {
        if (nextStop) {
            Gizmos.color = Color.green;
            Gizmos.DrawLine(transform.position, nextStop.transform.position);
        }
    }
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "train")
        {
            if (nextStop)
            myShip.track = nextStop;
            if (endLevel)
            {
                // Load the next level
            }
        }
    }
}

Oh yeah I should mention I have little experience modifying code to do things in the editor.

\$\endgroup\$
1
\$\begingroup\$

As Editor code goes, this is pretty straight forward, so don't worry. I would do it as a context menu for the component.

using UnityEngine;
using UnityEditor;

public class Rails : MonoBehaviour
{
    public Rails NextStop;

    [ContextMenu("Copy And Point")]
    public void DoThing()
    {
        var copy = Instantiate(gameObject);
        var rails = copy.GetComponent<Rails>();

        rails.NextStop = this;

        Selection.activeObject = copy;
    }
}

Then, in the inspector panel, you can right click on the rails component and select "Copy and Point."

Context Menu in Inspector

This will create a copy of the current game object and point the next stop to this one. The last line will make sure that the new object gets focus in the editor.

Hope it helps!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ It works I had to change Selection.activeObject = copy; into nextStop = copy and it work perfectly with my script thanks \$\endgroup\$ – Ryan Henry Oct 6 '15 at 6:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.