SOLVED: The variable “numofplayers” being public was the issue. public variables can only be changed in the editor. apparently the script will not change it. I removed public from the variable and my for loop was able to read it
This is my first post. I apologize if I break any posting rules. I am a beginner programmer but I understand the concepts well enough.
I’m making a local multiplayer game and I want to instantiate the proper number of players, with a for loop, based on a variable “numofplayers”. each player gets there respective "playerNum’ (max players will be 4)
i.e. “numofplayers = 2” then instantiate 2 players. the players will instantiate at “spawnpoints” which are empty game objects as usual.
my problem is the for loop is instantiating all 4 players when i use the variable “numofplayers” no matter what number i set it. if I manually enter the number into the for loop it instantiates the proper number.
my thought is THIS script should instantiate 2 players, but it instantiates all 4
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class gameController : MonoBehaviour {
public GameObject player;
public Transform[] spawnpoints;
public int numofplayers = 2;
// Use this for initialization
void Start () {
for (int i = 0; i < numofplayers; i++)
{
GameObject clone;
clone = Instantiate(player,spawnpoints*);*
clone.GetComponent().playerNum = i;
}
}
When i exchange “numofplayers” in the for loop with an actual integer like THIS. it instantiates 2
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class gameController : MonoBehaviour {
public GameObject player;
public Transform[] spawnpoints;
public int numofplayers = 2;
- // Use this for initialization*
- void Start () {*
for (int i = 0; i < 2; i++)
{
GameObject clone;
clone = Instantiate(player,spawnpoints*);*
clone.GetComponent().playerNum = i;
}
}
To reiterate. Why does the for loop not use the “numofPlayers” variable properly. the for loop works properly with an integer but not when i substitute the variable.
Thank you in advance for the help
bonus question: spawnpoints[] is a transform array. arrays start at 0. why does 2 in the for loop instantiate 2 player and not 3? is it because the foor loop starts at 0?