using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LightsEffect : MonoBehaviour
{
public List<UnityEngine.GameObject> waypoints;
public int howmanylight = 5;
public bool changeLightsDirection = false;
public bool twoSides = false;
public float delay = 0.1f;
private List<UnityEngine.GameObject> objects;
private Renderer[] renderers;
private int greenIndex = 0;
private float lastChangeTime;
private void Start()
{
objects = new List<UnityEngine.GameObject>();
if (howmanylight > 0)
{
UnityEngine.GameObject go1 = UnityEngine.GameObject.CreatePrimitive(PrimitiveType.Sphere);
duplicateObject(go1, howmanylight);
LightsEffects();
}
}
private void Update()
{
LightsEffectCore();
}
public void duplicateObject(UnityEngine.GameObject original, int howmany)
{
if (twoSides == true)
howmany = howmany * 2;
howmany++;
for (int i = 0; i < waypoints.Count - 1; i++)
{
for (int j = 1; j < howmany; j++)
{
Vector3 position = waypoints[i].transform.position + j * (waypoints[i + 1].transform.position - waypoints[i].transform.position) / howmany;
UnityEngine.GameObject go = Instantiate(original, new Vector3(position.x, 0.05f, position.z), Quaternion.identity);
go.transform.localScale = new Vector3(0.3f, 0.1f, 0.3f);
objects.Add(go);
}
}
}
private void LightsEffects()
{
renderers = new Renderer[objects.Count];
for (int i = 0; i < renderers.Length; i++)
{
renderers[i] = objects[i].GetComponent<Renderer>();
renderers[i].material.color = Color.red;
}
// Set green color to the first one
greenIndex = 0;
renderers[greenIndex].material.color = Color.green;
}
private void LightsEffectCore()
{
// Change color each `delay` seconds
if (Time.time > lastChangeTime + delay)
{
lastChangeTime = Time.time;
// Set color of the last renderer to red
// and the color of the current one to green
renderers[greenIndex].material.color = Color.red;
if (changeLightsDirection == true)
{
Array.Reverse(renderers);
changeLightsDirection = false;
}
greenIndex = (greenIndex + 1) % renderers.Length;
renderers[greenIndex].material.color = Color.green;
}
}
}
Inside the method duplicateObject I'm checking if the flag twoSides is true and then double by twice the amount of lights:
public void duplicateObject(UnityEngine.GameObject original, int howmany)
{
if (twoSides == true)
howmany = howmany * 2;
howmany++;
for (int i = 0; i < waypoints.Count - 1; i++)
{
for (int j = 1; j < howmany; j++)
{
Vector3 position = waypoints[i].transform.position + j * (waypoints[i + 1].transform.position - waypoints[i].transform.position) / howmany;
UnityEngine.GameObject go = Instantiate(original, new Vector3(position.x, 0.05f, position.z), Quaternion.identity);
go.transform.localScale = new Vector3(0.3f, 0.1f, 0.3f);
objects.Add(go);
}
}
}
This lines:
if (twoSides == true)
howmany = howmany * 2;
But this will add just more 5 lights between the waypoints like it show in the screenshot.
And I want it to add more 5 lights but to create two lines between the waypoints of lights line by line.
Somehow to change the new 5 lights position so it will be near/next the first 5 lights. And then to align the lines of lights so they will be equal between the waypoints.
Two lines and two sides I mean something like this:
But they should be equal between the waypoints like in the first screenshot.
What I tried is this:
Changed the duplicateObject method to:
public void duplicateObject(UnityEngine.GameObject original, int howmany)
{
GameObject go = new GameObject();
if (twoSides == true)
howmany = howmany * 2;
howmany++;
for (int i = 0; i < waypoints.Count - 1; i++)
{
for (int j = 1; j < howmany; j++)
{
Vector3 position = waypoints[i].transform.position + j * (waypoints[i + 1].transform.position - waypoints[i].transform.position) / howmany;
if (j > 5)
{
go = Instantiate(original, new Vector3(position.x + 1, 0.05f, position.z), Quaternion.identity);
}
else
{
go = Instantiate(original, new Vector3(position.x, 0.05f, position.z), Quaternion.identity);
}
go.transform.localScale = new Vector3(0.3f, 0.1f, 0.3f);
objects.Add(go);
}
}
}
But the result is not what I wanted:
Now the problem is that the lights the gaps between them is not equal between the two waypoints (cubes) and also the new 5 lights are two far from the waypoints.
Both lights each 5 lights should be with equal gaps and side by side between the waypoints. Like a landing lights for aircraft between the two waypoints.
Related
The script is a bit long I'm not sure what I can reduce I will try.
When I'm running the program it's starting by making the square formation.
What I'm trying to archive is that at each time in runtime if I change the numberOfSquadMembers value up or down add/remove to each squad the more/less value of squad members.
Same for the numberOfSquads value.
The problem is I'm not sure how to do it in the Update() how to add more squads/squadmemebers or destroy when the values are less then the current ?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class Formations : MonoBehaviour
{
enum Formation
{
Square, Circle, Triangle
}
[Header("Main Settings")]
[Space(5)]
[Range(4, 100)]
public int numberOfSquadMembers = 20;
[Range(1, 20)]
public int numberOfSquads = 1;
[Range(0, 4)]
public int columns = 4;
public int gaps = 10;
public int circleRadius = 10;
public float yOffset = 0;
[Range(3, 50)]
public float moveSpeed = 3;
[Range(3, 50)]
public float rotateSpeed = 1;
public float threshold = 0.1f;
public bool randomSpeed = false;
[Range(1, 100)]
public int randSpeedMin = 1;
[Range(1, 100)]
public int randSpeedMax = 1;
public bool startRandomFormation = false;
public string currentFormation;
private Formation formation;
private List<Quaternion> quaternions = new List<Quaternion>();
private List<Vector3> newpositions = new List<Vector3>();
private bool move = false;
private bool squareFormation = false;
private List<GameObject> squadMembers = new List<GameObject>();
private float[] step;
private int[] randomSpeeds;
private int index = 0;
private bool ready = false;
private GameObject[] squads;
private Vector3 startVector;
private Vector3 total;
private List<Vector3> endpositions = new List<Vector3>();
public void InitFormations()
{
if (startRandomFormation)
{
formation = (Formation)UnityEngine.Random.Range(0, Enum.GetNames(typeof(Formation)).Length);
}
else
{
formation = Formation.Square;
}
squads = GameObject.FindGameObjectsWithTag("Squad");
for (int i = 0; i < squads.Length; i++)
{
foreach (Transform squadMember in squads[i].transform)
{
squadMembers.Add(squadMember.gameObject);
}
}
foreach (GameObject unit in squadMembers)
{
if (unit != null)
{
total += unit.transform.position;
}
}
Vector3 center = total / squadMembers.Count;
//Vector3 endPos = GameObject.Find("Cube").transform.position;
foreach (GameObject unit in squadMembers)
{
startVector = unit.transform.position - center;
endpositions.Add(/*endPos + */startVector);
}
currentFormation = formation.ToString();
ChangeFormation();
randomSpeeds = RandomSpeeds(randSpeedMin, randSpeedMax, squadMembers.Count);
step = new float[squadMembers.Count];
ready = true;
}
private void Start()
{
InitFormations();
}
// Update is called once per frame
void Update()
{
if (ready == true)
{
if (Input.GetKeyDown(KeyCode.C))
{
randomSpeeds = RandomSpeeds(randSpeedMin, randSpeedMax, squadMembers.Count);
foreach (int speedV in randomSpeeds)
{
if (index == randomSpeeds.Length)
index = 0;
step[index] = speedV * Time.deltaTime;
index++;
}
ChangeFormation();
}
if (move == true)
{
MoveToNextFormation();
}
}
}
private void ChangeFormation()
{
switch (formation)
{
case Formation.Square:
FormationSquare();
break;
case Formation.Circle:
FormationCircle();
break;
case Formation.Triangle:
FormationTriangle();
break;
}
}
private void FormationTriangle()
{
newpositions = new List<Vector3>();
int height = Mathf.CeilToInt((Mathf.Sqrt(8 * squadMembers.Count + 1f) - 1f) / 2);
int slots = (int)(height * (height + 1f) / 2f);
float verticalModifier = 1.25f; // * 1.25f to increase horizontal space
float horizontalModifier = 0.8f; // * 0.8f to decrease "vertical" space
float width = 0.5f * (height - 1f);
Vector3 startPos = new Vector3(width * horizontalModifier, 0f, (float)(height - 1f) * verticalModifier);
int finalRowCount = height - slots + squadMembers.Count;
for (int rowNum = 0; rowNum < height && newpositions.Count < squadMembers.Count; rowNum++)
{
for (int i = 0; i < rowNum + 1 && newpositions.Count < squadMembers.Count; i++)
{
float xOffset = 0f;
if (rowNum + 1 == height)
{
// If we're in the last row, stretch it ...
if (finalRowCount != 1)
{
// Unless there's only one item in the last row.
// If that's the case, leave it centered.
xOffset = Mathf.Lerp(
rowNum / 2f,
-rowNum / 2f,
i / (finalRowCount - 1f)
) * horizontalModifier;
}
}
else
{
xOffset = (i - rowNum / 2f) * horizontalModifier;
}
float yOffset = (float)rowNum * verticalModifier;
Vector3 position = new Vector3(
startPos.x + xOffset, 0f, startPos.y - yOffset);
newpositions.Add(position);
}
}
move = true;
formation = Formation.Square;
}
private Vector3 FormationSquarePositionCalculation(int index) // call this func for all your objects
{
float posX = (index % columns) * gaps;
float posY = (index / columns) * gaps;
return new Vector3(posX, posY);
}
private void FormationSquare()
{
newpositions = new List<Vector3>();
quaternions = new List<Quaternion>();
for (int i = 0; i < squadMembers.Count; i++)
{
Vector3 pos = FormationSquarePositionCalculation(i);
//squadMembers[i].transform.position = new Vector3(transform.position.x + pos.x, 0, transform.position.y + pos.y);
squadMembers[i].transform.Rotate(new Vector3(0, -90, 0));
//newpositions.Add(new Vector3(transform.position.x + pos.x, 0, transform.position.y + pos.y));
newpositions.Add(new Vector3(endpositions[i].x + pos.x, 0, endpositions[i].y + pos.y));
}
move = true;
squareFormation = true;
formation = Formation.Circle;
}
private Vector3 FormationCirclePositionCalculation(Vector3 center, float radius, int index, float angleIncrement)
{
float ang = index * angleIncrement;
Vector3 pos;
pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
pos.z = center.z + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
pos.y = center.y;
return pos;
}
private void FormationCircle()
{
newpositions = new List<Vector3>();
quaternions = new List<Quaternion>();
Vector3 center = transform.position;
float radius = (float)circleRadius / 2;
float angleIncrement = 360 / squadMembers.Count;//(float)numberOfSquadMembers;
for (int i = 0; i < squadMembers.Count; i++)//numberOfSquadMembers; i++)
{
Vector3 pos = FormationCirclePositionCalculation(center, radius, i, angleIncrement);
var rot = Quaternion.LookRotation(center - pos);
if (Terrain.activeTerrain == true)
pos.y = Terrain.activeTerrain.SampleHeight(pos);
pos.y = pos.y + yOffset;
newpositions.Add(pos);
quaternions.Add(rot);
}
move = true;
squareFormation = false;
formation = Formation.Triangle;
}
private void MoveToNextFormation()
{
if (randomSpeed == false)
{
if (step.Length > 0)
step[0] = moveSpeed * Time.deltaTime;
}
for (int i = 0; i < squadMembers.Count; i++)
{
squadMembers[i].transform.LookAt(newpositions[i]);
if (randomSpeed == true)
{
squadMembers[i].transform.position =
Vector3.MoveTowards(squadMembers[i].transform.position, newpositions[i], step[i]);
}
else
{
squadMembers[i].transform.position =
Vector3.MoveTowards(squadMembers[i].transform.position, newpositions[i], step[0]);
}
if (Vector3.Distance(squadMembers[i].transform.position, newpositions[i]) < threshold)
{
if (squareFormation == true)
{
Vector3 degrees = new Vector3(0, 0, 0);
Quaternion quaternion = Quaternion.Euler(degrees);
squadMembers[i].transform.rotation = Quaternion.Slerp(squadMembers[i].transform.rotation, quaternion, rotateSpeed * Time.deltaTime);
}
else
{
squadMembers[i].transform.rotation = Quaternion.Slerp(squadMembers[i].transform.rotation, quaternions[i], rotateSpeed * Time.deltaTime);
}
}
}
}
private static int[] RandomSpeeds(int min, int max, int howMany)
{
int[] myNumbers = new int[howMany];
for (int i = 0; i < howMany; i++)
{
myNumbers[i] = UnityEngine.Random.Range(min, max);
}
return myNumbers;
}
}
This is the script that generate the squads and number of squads members first time :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SquadsGenerator : MonoBehaviour
{
public GameObject squadPrefab;
public int numberOfSquads;
public int numberOfMembersInsquad;
private GameObject squadsParent;
private void Start()
{
squadsParent = GameObject.Find("Squads");
GenerateSquads(numberOfSquads, numberOfMembersInsquad, squadPrefab);
}
// Update is called once per frame
void Update()
{
}
public void GenerateSquads(int squadsCount,
int numberOfMembers,
GameObject squadMemberPrefab)
{
for (int i = 0; i < squadsCount; i++)
{
GameObject newSquad = new GameObject();
newSquad.name = "Squad " + i;
newSquad.tag = "Squad";
newSquad.transform.parent = squadsParent.transform;
for (int x = 0; x < numberOfMembers; x++)
{
var go = Instantiate(squadMemberPrefab);
go.name = "Member " + x;
go.tag = "Squad Member";
go.transform.parent = newSquad.transform;
switch (i % 6)
{
case 0: ColorSquad(go, Color.green); break;
case 1: ColorSquad(go, Color.red); break;
case 2: ColorSquad(go, Color.blue); break;
case 3: ColorSquad(go, Color.yellow); break;
case 4: ColorSquad(go, Color.cyan); break;
case 5: ColorSquad(go, Color.magenta); break;
}
}
}
}
private void ColorSquad(GameObject squad, Color color)
{
Renderer rend = squad.GetComponent<Renderer>();
rend.material.SetColor("_Color", color);
}
}
Update :
What I have tried so far :
I added this part to the Update()
if(oldNumOfSquadMemebers != numberOfSquadMembers)
{
var tt = numberOfSquadMembers - oldNumOfSquadMemebers;
for (int i = 0; i < tt; i++)
{
var go = Instantiate(squadMemberPrefab);
squadMembers.Add(go);
}
oldNumOfSquadMemebers = numberOfSquadMembers;
FormationSquare();
}
The problem now is in the FormationSquare method :
private void FormationSquare()
{
newpositions = new List<Vector3>();
quaternions = new List<Quaternion>();
for (int i = 0; i < squadMembers.Count; i++)
{
Vector3 pos = FormationSquarePositionCalculation(i);
squadMembers[i].transform.Rotate(new Vector3(0, -90, 0));
newpositions.Add(new Vector3(endpositions[i].x + pos.x, 0, endpositions[i].y + pos.y));
}
move = true;
squareFormation = true;
formation = Formation.Circle;
}
Now I'm making a new instance for the newpositions List so each time I change the number of squad members there are more members but less newpositions so at some time I'm getting out of index exception.
If I don't make a new instance for the List then it will work but then after some time it will throw the out of index exception this time because it keep adding more and more new positions to the list.
So this newpositions List I'm stuck with it. Not sure how to solve it.
I'm trying to make a "Mania" style game(like guitar hero). But i can't seem to get the Movement of the "notes" to work, I keep the notes in a queue and I dequeue the last note and change it's position to the top again. But for some reason it doesen't work with my "goodcubes". only the normal ones
The problem seems to be that the instead of moving the "goodCube" to the correct position it instead changes the transform of the prefab.
All "notes" are referred to as "Cubes" in script
for (int i = 0; i < backlog; i++)//how many rows to spawn
{
goodCubes.Enqueue(Instantiate(goodcube));
for (int j = 0; j < columns - 1; j++)
{
badCubes.Enqueue(Instantiate(cube));
}
}
//I check the player input and if it corresponds with a note in the correct row
//I have tested so both true and false option gets called
if (i == position)
{
GameObject good = goodCubes.Dequeue();
good.transform.position = spawnPoint;
spawnPoint += new Vector2(1 * rowOffset, 0);
goodCubes.Enqueue(goodcube);
}
else
{
GameObject badCube = badCubes.Dequeue();
badCube.transform.position = spawnPoint;`enter code here`
spawnPoint += new Vector2(1 * rowOffset, 0);
badCubes.Enqueue(badCube);
}
The full script
public int columus;
public GameObject cube;
public GameObject goodcube;
public event Action moveCubes;
[SerializeField] private int score = 0;
[SerializeField] private float rowOffset = 1;
[SerializeField] private float heightDifference = 1;
[SerializeField] private int backlog = 4;
private float SpawnHeight;
Queue<int> positions = new Queue<int>();
Queue<GameObject> badCubes = new Queue<GameObject>();
Queue<GameObject> goodCubes = new Queue<GameObject>();
private void Start()
{
for (int i = 0; i < backlog; i++)
{
goodCubes.Enqueue(Instantiate(goodcube));
for (int j = 0; j < columus - 1; j++)
{
badCubes.Enqueue(Instantiate(cube));
}
}
for (int i = 0; i < backlog; i++)
{
positions.Enqueue(SpawnRow(i * heightDifference));
}
}
int SpawnRow(float y)
{
int position = UnityEngine.Random.Range(0, columus);
Vector2 spawnPoint = new Vector2(-columus * rowOffset / 2f, y);
for (int i = 0; i < columus; i++)
{
if (i == position)
{
GameObject goodCube = goodCubes.Dequeue();
goodCube.transform.position = spawnPoint;
spawnPoint += new Vector2(1 * rowOffset, 0);
goodCubes.Enqueue(goodcube);
}
else
{
GameObject badCube = badCubes.Dequeue();
badCube.transform.position = spawnPoint;
spawnPoint += new Vector2(1 * rowOffset, 0);
badCubes.Enqueue(badCube);
}
}
return position;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.D))
{
UpdateScore(0);
}
else if (Input.GetKeyDown(KeyCode.F))
{
UpdateScore(1);
}
else if (Input.GetKeyDown(KeyCode.J))
{
UpdateScore(2);
}
else if (Input.GetKeyDown(KeyCode.K))
{
UpdateScore(3);
}
} //inputcheck
private void UpdateScore(int input)
{
if (positions.Dequeue() == input)
{
moveCubes?.Invoke();
positions.Enqueue(SpawnRow(backlog * heightDifference + 1 * heightDifference));
score++;
}
else
{
moveCubes?.Invoke();
positions.Enqueue(SpawnRow(backlog * heightDifference + 1 * heightDifference));
score--;
}
}
I truly believe your issue is a typo in your code. That usually happens when you have variables with the same name. Your issue is that you are enqueuing the prefab goodcube and not the goodCube object:
GameObject goodCube = goodCubes.Dequeue();
goodCube.transform.position = spawnPoint;
spawnPoint += new Vector2(1 * rowOffset, 0);
//******HERE YOU ARE ENQUEUEING THE PREFAB goodcube AND NOT goodCube as your variable name suggests two lines above this line*****
goodCubes.Enqueue(goodCube);//INSTEAD OF goodCubes.Enqueue(goodcube);
The problem is in the LightsEffectCore when I make the array reverse.
The lights change direction but not from the current light it is on.
It's jumping to some other light index and change the direction from there.
And I want it to change the direction from the current light index.
If the light is now on index 5 and I change the direction then move from 5 to 4 and if I changed the direction again move from 4 to 5.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LightsEffect : MonoBehaviour
{
public List<UnityEngine.GameObject> waypoints = new List<UnityEngine.GameObject>();
public int howmanylight = 5;
public Generatenumbers gn;
public bool changeLightsDirection = false;
public float delay = 0.1f;
private List<UnityEngine.GameObject> objects;
private Renderer[] renderers;
private int greenIndex = 0;
private float lastChangeTime;
private void Start()
{
objects = new List<UnityEngine.GameObject>();
if (howmanylight > 0)
{
UnityEngine.GameObject go1 = UnityEngine.GameObject.CreatePrimitive(PrimitiveType.Sphere);
duplicateObject(go1, howmanylight);
LightsEffects();
}
}
private void Update()
{
LightsEffectCore();
}
public void duplicateObject(UnityEngine.GameObject original, int howmany)
{
howmany++;
for (int i = 0; i < waypoints.Count - 1; i++)
{
for (int j = 1; j < howmany; j++)
{
Vector3 position = waypoints[i].transform.position + j * (waypoints[i + 1].transform.position - waypoints[i].transform.position) / howmany;
UnityEngine.GameObject go = Instantiate(original, new Vector3(position.x, 0, position.z), Quaternion.identity);
go.transform.localScale = new Vector3(0.3f, 0.1f, 0.3f);
objects.Add(go);
}
}
}
private void LightsEffects()
{
renderers = new Renderer[objects.Count];
for (int i = 0; i < renderers.Length; i++)
{
renderers[i] = objects[i].GetComponent<Renderer>();
renderers[i].material.color = Color.red;
}
// Set green color to the first one
greenIndex = 0;
renderers[greenIndex].material.color = Color.green;
}
private void LightsEffectCore()
{
// Change color each `delay` seconds
if (Time.time > lastChangeTime + delay)
{
lastChangeTime = Time.time;
// Set color of the last renderer to red
// and the color of the current one to green
renderers[greenIndex].material.color = Color.red;
if (changeLightsDirection == true)
{
Array.Reverse(renderers);
changeLightsDirection = false;
}
greenIndex = (greenIndex + 1) % renderers.Length;
renderers[greenIndex].material.color = Color.green;
}
}
}
You have to change your greenIndex as well, when you reversing the array. If you do not, then the new value at that index is going to be the one after the reverse, and that is why, it looks like it is jumping away.
If you want to avoid it jumping about, set the index to greenIndex=renderers.Lenght-greenIndex.
I could not test it out, please correct me if I am wrong.
Hey guys I'm making a Terraria-like game, I've been creating the biomes but have been having trouble rendering the chunks. I've put the second code in a "GameMaster" gameobject in the game. And used Gameobject Chunk in the second code to attach a gameobject with the first code. For some reason my GetComponent<>().width; doesn't recognize the ChunkGenerator class. Therefore giving me errors. Anything helps. Thanks. I've attached the two codes below.
Here's the first code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChunkGenerator : MonoBehaviour {
public GameObject DirtTile;
public GameObject StoneTile;
public GameObject GrassTile;
public GameObject SandTile;
public int heightAddition;
public int width;
public float heightMultiplier;
float worldSeed;
float playerSpawnBiome;
public float smoothness;
public float mountSmooth;
void Start () {
// playerSpawnBiome = Random.Range (-5f, 10f);
// if (playerSpawnBiome > 0f) {
// GenerateMountainBiome ();
// } else if ((playerSpawnBiome > 0f) && (playerSpawnBiome <= 5f)) {
GeneratePlainsBiome ();
// } else {
// GenerateSandBiome ();
// }
}
public void GeneratePlainsBiome() {
worldSeed = Random.Range (-10000f, 10000f);
for (int i = 0; i < width; i++)
{
int h = Mathf.RoundToInt(Mathf.PerlinNoise (worldSeed, (i + transform.position.x / smoothness) * heightMultiplier) + heightAddition);
for (int j = 0; j < h; j++) {
GameObject selectedTile;
if (j < h - 3) {
selectedTile = StoneTile;
} else if (j < h - 1) {
selectedTile = DirtTile;
} else {
selectedTile = GrassTile;
}
GameObject newTile = Instantiate (selectedTile, Vector3.zero, Quaternion.identity) as GameObject;
newTile.transform.parent = this.gameObject.transform;
newTile.transform.localPosition = new Vector3 (i, j);
}
}
}
public void GenerateSandBiome() {
worldSeed = Random.Range (-10000f, 10000f);
for (int i = 0; i < width; i++)
{
int h = Mathf.RoundToInt(Mathf.PerlinNoise (worldSeed, (i / smoothness) * heightMultiplier) + heightAddition);
for (int j = 0; j < h; j++) {
GameObject selectedTile;
if (j < h - 3) {
selectedTile = StoneTile;
} else if (j < h - 1) {
selectedTile = SandTile;
} else {
selectedTile = SandTile;
}
Instantiate (selectedTile, new Vector3(i, j), Quaternion.identity);
}
}
}
public void GenerateMountainBiome() {
worldSeed = Random.Range (-10000f, 10000f);
for (int i = 0; i < width; i++)
{
int h = Mathf.RoundToInt(Mathf.PerlinNoise (worldSeed, (i / 3f) * mountSmooth) * heightMultiplier) + heightAddition;
for (int j = 0; j < h; j++) {
GameObject selectedTile;
if (j < h - 3) {
selectedTile = StoneTile;
} else if (j < h - 1) {
selectedTile = DirtTile;
} else {
selectedTile = GrassTile;
}
Instantiate (selectedTile, new Vector3(i, j), Quaternion.identity);
}
}
}
}
Here's the second Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChunkGenerators : MonoBehaviour {
public GameObject chunk;
int chunkWidth;
public int numChunks;
float seed;
void Start() {
chunkWidth = chunk.GetComponent<ChunkGenerator> ().width;
seed = Random.Range (-1000000f, 1000000f);
Generate ();
}
public void Generate() {
int lastX = -chunkWidth;
for (int i = 0; i < numChunks; i++) {
GameObject newChunk = Instantiate (chunk, new Vector3 (lastX + chunkWidth, 0f), Quaternion.identity) as GameObject;
newChunk.GetComponent<ChunkGenerator> ().seed = seed;
lastX += chunkWidth;
}
}
}
Its because you are referencing the wrong script. You're mistakingly referencing ChunkGenerator instead of ChunkGenerators.
Change:
newChunk.GetComponent<ChunkGenerator> ().seed = seed;
to
newChunk.GetComponent<ChunkGenerators> ().seed = seed;
I'm new to Unity and am trying to create the chess board background in unity. I need the scene to be full of cubes using the prefab I created. When the counter is even, the cube is set to black else to red. I don't know what is going on really because nothing is showing up when z is 0. This is my code..
public GameObject pre;
public int counter = 0;
public int worldWidth = 20;
public int worldHeight = 20;
private float positionX;
private float positionY;
void Start()
{
chessBoardCube = Resources.Load<GameObject>("Prefabs/pre");
positionX = -11.24f;
positionY = 4.8f;
counter = 0;
}
void Update()
{
for (int x = 0; x < worldWidth; x++)
{
for (int z = 0; z < worldHeight; z++)
{
if (counter % 2 == 0)
{
GameObject block = Instantiate(pre, Vector3.zero, Quaternion.identity) as GameObject;
block.renderer.material.color = Color.black;
block.transform.parent = transform;
float xP = positionX * 3;
float yP = positionY * z;
block.transform.localScale = new Vector3(2, 2, 1);
block.transform.localPosition = new Vector3(xP, 0);
}
else
{
GameObject block = Instantiate(pre, Vector3.zero, Quaternion.identity) as GameObject;
block.renderer.material.color = Color.red;
block.transform.parent = transform;
float xP = positionX * x;
float yP = positionY * z;
block.transform.localScale = new Vector3(2, 2, 1);
block.transform.localPosition = new Vector3(xP, 0);
}
}
counter++;
}
}
The positionX and positionY variables are the position that the prefab is set.
Any help would be appreciated.
Thanks!
I'd suggest something like this:
public GameObject pre;
public int worldWidth = 20;
public int worldHeight = 20;
public float cubeSize = 2;
private float positionX;
private float positionY;
private float positionZ;
void Start()
{
chessBoardCube = Resources.Load<GameObject>("Prefabs/pre");
positionX = -11.24f;
positionY = 4.8f;
positionZ = 0.0f;
}
//Probably unwanted in update
void Update()
{
for (int x = 0; x < worldWidth; x++)
{
for (int y = 0; y < worldHeight; y++)
{
GameObject block = Instantiate(pre, Vector3.zero, Quaternion.identity) as GameObject;
block.transform.parent = transform;
if(x%2 == 0) {
if(y%2 == 0) {
block.renderer.material.color = Color.black;
} else {
block.renderer.material.color = Color.red;
}
} else {
if(y%2 == 0) {
block.renderer.material.color = Color.red;
} else {
block.renderer.material.color = Color.black;
}
}
float xP = positionX + x*cubeSize;
float yP = positionY + y*cubeSize;
block.transform.localScale = new Vector3(cubeSize, cubeSize, 1);
block.transform.localPosition = new Vector3(xP, yP, positionZ);
}
}
}
void generateBoard(){
float tempX = cubePrefab.transform.localScale.x;
float tempY = cubePrefab.transform.localScale.y;
float tempZ = cubePrefab.transform.localScale.z;
for (int i = 0; i < boardLength; i++) {
tempX = cubePrefab.transform.localScale.x;
for (int j = 0; j < boardWidth; j++) {
GameObject block = Instantiate(cubePrefab, parentTransform) as GameObject;
block.transform.localPosition = new Vector3(tempX , tempY , tempZ);
tempX += cubePrefab.transform.localScale.x;
if(i%2 == 0){
if(j%2 == 0){
block.GetComponent<Renderer>().material.color = Color.white;
}else{
block.GetComponent<Renderer>().material.color = Color.black;
}
}else{
if(j%2 == 0){
block.GetComponent<Renderer>().material.color = Color.black;
}else{
block.GetComponent<Renderer>().material.color = Color.white;
}
}
}
tempZ += cubePrefab.transform.localScale.z;
}
}