Search code examples
c#unity-game-enginevectorlevels

Is it possible to include a variable inside of a vector3?


I trying to make a game kind of like slope, where there are new obstacles every 3 seconds. Instead of making infinite spawn points, I thought of making the first one and change the z by 20 pixels. the problem is I don't know how I can make a Vector3 storing 2 integers and a variable.

I'm kind of stuck so I haven't tried anything since I don't know what to try.

using System.Collections.Generic;
using UnityEngine;

public class levelgen : MonoBehaviour

{
    private int count = 9;
    public GameObject[] templates;


    // Update is called once per frame
    void Update()
    {
        public Vector3 spawn = new Vector3(-2, 0, count);
        int rand = Random.RandomRange(1, 5); //1-5 types of levels
        Instantiate(templates[rand], spawn1, Quaternion.identity);
        count = count + 20;

    }
}

I want to store the variable count in the Vector3 spawn.


Solution

  • Sure you can .. but it will not be called count anymore but e.g. z

    public class levelgen : MonoBehaviour
    {
        // You can not declare a public field within a method
        // so move it to class scope
        public Vector3 spawn = new Vector3(-2, 0, 9);
        public GameObject[] templates;
    
        // Update is called once per frame
        void Update()
        {
            // Here NOTE that for int parameters the second argument is "exclusiv"
            // so if you want correct indices you should always rather use
            int rand = Random.RandomRange(0, templates.Length);
            // I will just assume a typo and use spawn instead of spawn1
            Instantiate(templates[rand], spawn, Quaternion.identity);
    
            spawn.z += 20;
    
            // Or I would prefer since this works in general
            // Vector3.forward is a shorthand for writing new Vector3(0, 0, 1)
            // and this works in general
            spawn += Vector3.forward * 20;
    
            // you can e.g. NOT use
            //transform.position.z += 20
            // but only
            //transform.position += Vector3.forward * 20;
        }
    }
    

    Note Having this code Instantiate a new object every frame in general is a very bad idea. If you really need so many objects checkout Object Pooling