user8019080
user8019080

Reputation:

Moving object to position of another object on button press

I am attempting to make a random spawn system, the randomising works however the objects never move to the position. I have broken it down to now just one of the objects moving to the spawn point when space is pressed. However, the object does not move and I am unsure on what to try next.

 public Transform spawn1;
public Transform spawn2;
public Transform spawn3;

public Transform obj1;
public Transform obj2;
public Transform obj3;

private Transform[] spawns = new Transform[3];
private Transform[] objects = new Transform[3];

private bool[] spawnUsed = new bool[3];
private bool[] objectUsed = new bool[3];

private int randomRun = 0;

void Start()
{ 

    spawns[0] = spawn1;
    spawns[1] = spawn2;
    spawns[2] = spawn3;

    objects[0] = obj1;
    objects[1] = obj2;
    objects[2] = obj3;
}

void Update()
{
    if (Input.GetKeyDown("space"))
    {
        // RandomChoice();

       // int ran = Random.Range(0, 2);

        obj1.transform.position = spawn1.transform.position;

        Debug.Log("Moved");
    }
}

I have tried both the objects and spawns as transforms and game objects but it doesn't make a difference. When space is pressed the debug "Moved" does show in the lof but nothing else happens.

Upvotes: 0

Views: 183

Answers (1)

Jack Mariani
Jack Mariani

Reputation: 2408

One of your references is pointing to a prefab and not to a scene object.

First you need to check which one is the prefab, and you might do that by checking its scene.rootCount == 0.

Then you either instantiate it, or select it from the scene.

You can apply this code if you plan for instantiation:

void Update()
{
    if (Input.GetKeyDown("space"))
    {
        // int ran = Random.Range(0, 2);
        Debug.Log("Is obj1 a prefab" + (obj1.gameObject.scene.rootCount == 0));
        Debug.Log("Is spawn1 a prefab" + (spawn1.gameObject.scene.rootCount == 0));

        // --------------- Check the object --------------- //
        Transform yourObject;
        if (obj1.gameObject.scene.rootCount == 0) yourObject = Instantiate(obj1);
        else yourObject = obj1;

        // --------------- Check the spawn --------------- //
        Transform spawn;
        if (spawn1.gameObject.scene.rootCount == 0) spawn = Instantiate(spawn1);
        else spawn                                        = spawn1;

        yourObject.position = spawn.position;

        Debug.Log("Moved");
    }
}

When you have found which one is the prefab you may decide to reference it directly from the scene (drag an object from the scene hierarchy instead of dragging it from the project window).

Otherwise you can just instantiate it (that maybe is just what you're trying to do).

Upvotes: 1

Related Questions