Clone an Instantiated Object many times Unity3D - c#

I have a list of prefabs, the script below instantiate 10 of them randomly in the Y axis.
The instantiated prefabs are random and different, but I want them to be same (clones of one prefab), how can I do that?
Script:
public GameObject[] Bricks;
void Start () {
SpawnCubes();
}
void SpawnBricks(int numCubes = 10, float startY = 3, float delta = 1)
{
for (int i = 0; i < numCubes; ++i)
{
int Rand = Random.Range(0, Bricks.Length);
var Brick = Instantiate(Bricks[Rand], new Vector3(0, startY - (float)i * delta, 0), Quaternion.identity);
Brick.transform.parent = gameObject.transform;
}
}
}

void SpawnBricks(int numCubes = 10, float startY = 3, float delta = 1)
{
int Rand = Random.Range(0, Bricks.Length);
for (int i = 0; i < numCubes; ++i)
{
var Brick = Instantiate(Bricks[Rand], new Vector3(0, startY - (float)i * delta, 0), Quaternion.identity);
Brick.transform.parent = gameObject.transform;
}
}
Like This??

Related

Physics.Raycast not working with a Marching Cubes -generated mesh

What it spits out
My raycast spits out a position way off from what it's supposed to be. I'm trying to place objects procedurally on a procedural mesh. I've been scratching my head at this for a while. Please help.
Sorry for the long script.
The start of the code is just some declares and stuff. GenObjects is run once in FixedUpdate after Start has finished. I'm using a marching cubes library by Scrawk and a noise library by Auburn
void GenMesh()
{
Marching marching = new MarchingCubes();
marching.Surface = 0.0f;
voxels = new float[width * height * length];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
for (int z = 0; z < length; z++)
{
float fx = x / (width - 1.0f);
float fy = y / (height - 1.0f);
float fz = z / (length - 1.0f);
int idx = x + y * width + z * width * height;
float surfaceHeight = noise2.GetNoise(x,z) * amplitude + offset;
float currentHeight = Mathf.Clamp(y, surfaceHeight - threshold, surfaceHeight + threshold);
float t = Mathf.Abs(currentHeight - surfaceHeight) / threshold;
voxels[idx] = Mathf.Lerp(Mathf.Clamp(noise.GetNoise(x,y,z), 0.65f, 1), -1f, t);
}
}
}
List<Vector3> verts = new List<Vector3>();
List<int> indices = new List<int>();
marching.Generate(voxels, width, height, length, verts, indices);
int maxVertsPerMesh = 30000;
int numMeshes = verts.Count / maxVertsPerMesh + 1;
for (int i = 0; i < numMeshes; i++)
{
List<Vector3> splitVerts = new List<Vector3>();
List<int> splitIndices = new List<int>();
for (int j = 0; j < maxVertsPerMesh; j++)
{
int idx = i * maxVertsPerMesh + j;
if (idx < verts.Count)
{
splitVerts.Add(verts[idx]);
splitIndices.Add(j);
}
}
if (splitVerts.Count == 0) continue;
Mesh mesh = new Mesh();
mesh.SetVertices(splitVerts);
mesh.SetTriangles(splitIndices, 0);
mesh.RecalculateBounds();
mesh.RecalculateNormals();
MeshWelder meshWelder = new MeshWelder(mesh);
meshWelder.Weld();
GameObject go = new GameObject("Mesh");
go.layer = LayerMask.NameToLayer("Ground");
go.transform.parent = transform;
go.transform.localScale = new Vector3(100f, 100f, 100f);
go.AddComponent<MeshFilter>();
go.AddComponent<MeshRenderer>();
go.AddComponent<MeshCollider>();
go.GetComponent<Renderer>().material = m_material;
go.GetComponent<MeshFilter>().mesh = mesh;
go.GetComponent<MeshCollider>().sharedMesh = mesh;
go.GetComponent<MeshCollider>().contactOffset = 0f;
go.transform.localPosition = new Vector3(-width * 100 / 2, -height * 100 / 4, -length * 100 / 2);
meshes.Add(go);
}
}
void GenObjects(GameObject prefab, float radius, Vector2 sampleRegionSize, Vector2 origin, int seed)
{
List<Vector2> points = PoissonDiscSampling.GeneratePoints(radius, sampleRegionSize, seed);
Physics.queriesHitBackfaces = true;
foreach (Vector2 point in points)
{
RaycastHit hit;
Vector3 objPos = new Vector3(0,0,0);
bool validPosFound = false;
if (Physics.Raycast(new Vector3(point.x + origin.x, 0, point.y + origin.y), Vector3.down, out hit, height * 100, layerMask))
{
objPos = hit.point;
validPosFound = true;
} else if (Physics.Raycast(new Vector3(point.x + origin.x, 0, point.y + origin.y), Vector3.up, out hit, height * 100, layerMask))
{
objPos = hit.point;
validPosFound = true;
}
if (validPosFound)
{
GameObject newObject = Instantiate(prefab, objPos, Quaternion.Euler(0, 0, 0));
}
}
Physics.queriesHitBackfaces = false;
}
}
Fixed! My mistake was really stupid. I wasn't assigning the welded mesh, leaving a filthy mesh with lots of empty verts floating about. The raycast was hitting them.
The fixed lines for anyone who cares:
Mesh mesh = new Mesh();
Mesh mesh_temp = new Mesh();
mesh_temp.SetVertices(splitVerts);
mesh_temp.SetTriangles(splitIndices, 0);
mesh_temp.RecalculateBounds();
mesh_temp.RecalculateNormals();
MeshWelder meshWelder = new MeshWelder();
meshWelder.customMesh = new CustomMesh();
meshWelder.customMesh.vertices = splitVerts.ToArray();
meshWelder.customMesh.triangles = splitIndices.ToArray();
meshWelder.customMesh.normals = mesh_temp.normals;
meshWelder.Weld();
mesh.SetVertices(meshWelder.customMesh.vertices);
mesh.SetTriangles(meshWelder.customMesh.triangles, 0);
mesh.SetNormals(meshWelder.customMesh.normals);
mesh.RecalculateBounds();

Mandelbrot Set function crashes

i made a sim for the Mandelbrot Set function, zn + 1 = power(zn) + c
and it work but when i get to the point were the function is unstable it crashes, now i have a boolen that when true makes a wire that connects all the circles, when its false its fine(dosent crash) but when its on it does, the code works like this:
start:
building a list of circles and making there pos by the equation, and then crating a wire between the circle and the last circle,
update:
then when you move the circle it uses the already made list of gameobj to update there pos.
you can try it here:
build
github:
git
but it crashes:(, heres the code:
private void updateCircles()
{
StartUpdateCircles();
}
private void StartCircles()
{
float x = BlackCircle.anchoredPosition.x;
float y = BlackCircle.anchoredPosition.y;
AllCircles.Add(BlackCircle.gameObject);
for (int i = 1; i < itarations; i++)
{
Vector2 RedCircleVec2 = RedCircle.anchoredPosition;
Vector2 LastCircleVec2 = AllCircles[i - 1].GetComponent<RectTransform>().anchoredPosition;
GameObject Circle = Instantiate(BlackCircle.gameObject, Vector3.zero, Quaternion.identity);
Circle.transform.SetParent(CanvasPerent);
AllCircles.Add(Circle);
x = Mathf.Pow(x, 2);
x -= Mathf.Pow(LastCircleVec2.y, 2);
x += RedCircleVec2.x;
y = (2 * LastCircleVec2.x
* LastCircleVec2.y) + RedCircleVec2.y;
Circle.GetComponent<RectTransform>().anchoredPosition = new Vector2(x, y);
if (HasWire)
{
GameObject wire = GenrateWireStart(LastCircleVec2
, Circle.GetComponent<RectTransform>().anchoredPosition);
AllWires.Add(wire);
}
}
}
private void StartUpdateCircles()
{
float x = BlackCircle.anchoredPosition.x;
float y = BlackCircle.anchoredPosition.y;
for (int i = 1; i < itarations; i++)
{
Vector2 RedCircleVec2 = RedCircle.anchoredPosition;
Vector2 LastCircleVec2 = AllCircles[i - 1].GetComponent<RectTransform>().anchoredPosition;
RectTransform ICircle = AllCircles[i].GetComponent<RectTransform>();
x = Mathf.Pow(x, 2);
x -= Mathf.Pow(LastCircleVec2.y, 2);
x += RedCircleVec2.x;
y = (2 * LastCircleVec2.x
* LastCircleVec2.y) + RedCircleVec2.y;
ICircle.anchoredPosition = new Vector2(x, y);
if (HasWire)
{
GenrateWireUpdate(LastCircleVec2
,ICircle.anchoredPosition, i);
}
}
}
public GameObject GenrateWireStart(Vector2 NodeA, Vector2 NodeB)
{
GameObject Connector = new GameObject("connector", typeof(Image));
Connector.transform.SetParent(CanvasPerent);
RectTransform ConnectorRT = Connector.GetComponent<RectTransform>();
ConnectorRT.anchorMin = new Vector2(0, 0);
ConnectorRT.anchorMax = new Vector2(0, 0);
Connector.GetComponent<Image>().color = new Color(0f, 0f, 0f, 0.25f);
Vector2 dir = (NodeB - NodeA).normalized;
float distance = Vector2.Distance(NodeA, NodeB);
ConnectorRT.sizeDelta = new Vector2(distance, 0.005f);
ConnectorRT.position = NodeA + dir * distance * .5f;
ConnectorRT.localEulerAngles = new Vector3(0, 0, UtilsClass.GetAngleFromVectorFloat(dir));
return Connector;
}
public void GenrateWireUpdate(Vector2 NodeA, Vector2 NodeB, int i)
{
RectTransform ConnectorRT = AllWires[i - 1].GetComponent<RectTransform>();
Vector2 dir = (NodeB - NodeA).normalized;
float distance = Vector2.Distance(NodeA, NodeB);
ConnectorRT.sizeDelta = new Vector2(distance, 0.005f);
ConnectorRT.position = NodeA + dir * distance * .5f;
ConnectorRT.localEulerAngles = new Vector3(0, 0, UtilsClass.GetAngleFromVectorFloat(dir));
}
pls help, thank you.
I looked briefly into your code and you seem to get some invalid positions like infinite / undefined from your calculations or just some positions too far away for Unity.
I could remove these by simply limiting positions to e.g.
x = Mathf.Clamp(Mathf.Pow(x, 2), -Screen.width, Screen.width);
x = Mathf.Clamp(x - Mathf.Pow(LastCircleVec2.y, 2), -Screen.width, Screen.width);
x = Mathf.Clamp(x + RedCircleVec2.x, -Screen.width, Screen.width);
y = Mathf.Clamp((2 * LastCircleVec2.x * LastCircleVec2.y) + RedCircleVec2.y, -Screen.width, Screen.width);
which simply limits all positions to some off-screen max positions

How can I make a circle from grid of GameObjects?

What I am trying to achieve is something like this:
What I have so far is the edges for the circles.
I know this would involve a nested for loop. This is what I have so far:
public GameObject player;
private GameObject playerGrid;
public int numOfObjects;
private Vector3 centerPos;
public int size = 2;
public Vector2 speed = new Vector2(50, 50);
private float smoothTime = 0.25f;
void Start()
{
playerGrid = new GameObject();
centerPos = transform.position;
for (int i = 0; i < numOfObjects; i++)
{
float pointNum = (i * 1.0f) / numOfObjects;
float angle = pointNum * Mathf.PI * 2;
float r = size / 2 * (Mathf.PI);
float x = Mathf.Sin(angle) * r;
float y = Mathf.Cos(angle) * r;
Vector3 pointPos = new Vector3(x, y, 0) + centerPos;
GameObject obj = Instantiate(player, pointPos, Quaternion.identity);
obj.transform.SetParent(playerGrid.transform);
}
}
I am stuck on how to implement the conditional for the nested for loop. Also, I have trouble understanding the calculations of column positions in the nested for loop. I believe the conditional would be the start and end of I for that column or row: for(int j = i + 1; j < i - 1, j++)
For the col positions, I would think it would be incrementing the angle enough to give the square its space for that column: float x = (Mathf.Sin(angle) + somethingHere) * r;
I just not sure how to progress from here.
Here's a simple way to draw a circle:
public float circleRadius = 5f;
public float objectSize = 1f;
void OnDrawGizmos()
{
for (var x = -circleRadius; x <= circleRadius; x++)
{
for (var y = -circleRadius; y <= circleRadius; y++)
{
var pos = new Vector3(x, 0f, y);
if (pos.magnitude >= circleRadius) continue;
Gizmos.DrawSphere(pos * (objectSize * 2f), objectSize);
}
}
}

Can I have some help optimizing this script

I wrote a infinite terrain script which works! Saddly everytime the player moves a chunk it lags for a moment. I know my code isn't great but I'm here to learn why :D
I'm unsure of what else to do. I've looked online and found no simple or understandable solution to me because I just don't know enough so I tried to write it on my own and it works but barley.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GEN_InfiniteTerrain : MonoBehaviour
{
public GameObject targetObject;
public GameObject chunkObject;
public int chunkSize;
public float unitSize;
public int renderDistance;
Dictionary<Vector2, GameObject> gridOfChunks = new Dictionary<Vector2, GameObject>();
List<Vector2> expectedChunkGridPositions = new List<Vector2>();
public float noiseScale;
// Infinite terrain values
float absoluteChunkSize;
private void Start()
{
// Calculate absolute chunk size
GetAbsoluteChunkSize();
// Generate base world
GenerateBase();
}
Vector2 lastTargetGridPosition = Vector2.zero;
private void LateUpdate()
{
// Get the targets position in world space
Vector3 targetAbsolutePosition = targetObject.transform.position;
// Convert the targets world position to grid position (/ 10 * 10 is just rounding to 10)
Vector2 targetGridPosition = new Vector2();
targetGridPosition.x = Mathf.RoundToInt(targetAbsolutePosition.x / 10) * 10 / absoluteChunkSize;
targetGridPosition.y = Mathf.RoundToInt(targetAbsolutePosition.z / 10) * 10 / absoluteChunkSize;
if (targetGridPosition - lastTargetGridPosition != Vector2.zero)
{
GenerateExpectedChunkAreas(targetGridPosition);
UpdateChunkPositions(targetGridPosition);
}
lastTargetGridPosition = targetGridPosition;
}
void GenerateBase()
{
for (int x = -renderDistance / 2; x < renderDistance / 2; x++)
{
for (int z = -renderDistance / 2; z < renderDistance / 2; z++)
{
Vector2 gridPosition = new Vector2(x, z);
Vector3 worldPosition = new Vector3(x * (unitSize * chunkSize), 0, z * (unitSize * chunkSize));
GameObject chunk = Instantiate(chunkObject, worldPosition, Quaternion.identity);
chunk.GetComponent<GEN_Chunk>().gridPosition = gridPosition;
gridOfChunks.Add(gridPosition, chunk);
}
}
GenerateExpectedChunkAreas(Vector2.zero);
}
void GenerateExpectedChunkAreas(Vector2 targetGridPosition)
{
expectedChunkGridPositions.Clear();
for (int x = -renderDistance / 2; x < renderDistance / 2; x++)
{
for (int z = -renderDistance / 2; z < renderDistance / 2; z++)
{
Vector2 gridPosition = new Vector2(x, z) + targetGridPosition;
expectedChunkGridPositions.Add(gridPosition);
}
}
}
void UpdateChunkPositions(Vector2 targetGridPosition)
{
List<Vector2> positionsWithoutChunks = new List<Vector2>();
List<Vector2> positionsWithOldChunks = new List<Vector2>();
for (int chunkCount = 0, x = -renderDistance / 2; x < renderDistance / 2; x++)
{
for (int z = -renderDistance / 2; z < renderDistance / 2; z++)
{
Vector2 gridPosition = new Vector2(x, z) + targetGridPosition;
if(!gridOfChunks.ContainsKey(gridPosition))
{
positionsWithoutChunks.Add(gridPosition);
}
chunkCount++;
}
}
foreach (GameObject chunk in gridOfChunks.Values)
{
if(!expectedChunkGridPositions.Contains(chunk.GetComponent<GEN_Chunk>().gridPosition))
{
positionsWithOldChunks.Add(chunk.GetComponent<GEN_Chunk>().gridPosition);
}
}
for (int i = 0; i < positionsWithOldChunks.Count; i++)
{
Vector3 worldPosition = new Vector3(positionsWithoutChunks[i].x * absoluteChunkSize, 0, positionsWithoutChunks[i].y * absoluteChunkSize);
gridOfChunks[positionsWithOldChunks[i]].transform.position = worldPosition;
// Recalculating noise for chunk based on its new position does lag more but even WITHOUT this it still stutters when player moves around. ( plan to learn threading just to calculate noise on seperate threads )
// gridOfChunks[positionsWithOldChunks[i]].GetComponent<GEN_Chunk>().ApplyNoise();
}
}
void GetAbsoluteChunkSize()
{
absoluteChunkSize = unitSize * chunkSize;
}
}
I need some smooth working infinite terrain (in quotes 'infinite')
And I'd like to learn too!

Unity 5 Randomly generated moving objects that slowly approach

this code is suppose to generate randomly placed clouds and planes in the distance that will fly towards you while the objective is to dodge them, however it just spawns random planes that don't move. It just gradually spawns them closer to your plane and keeps spawning them even if it goes past it, while the ones previously spawned stay in the same spot, so it's just a trail of non-moving planes, how would I code it so they approach me? Anything helps, thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CloudGen : MonoBehaviour {
public GameObject cloud;
public GameObject enemy;
int firstRand;
int secondRand;
int distance = 12;
int time = 0;
float x;
float y;
float z;
Vector3 intPos;
void Update () {
if (Input.GetButtonDown ("left") || Input.GetButtonDown ("right"))
{
firstRand = Random.Range (1, 3);
if(firstRand == 1)
{
secondRand = Random.Range (1, 3);
GameObject cloudInt = Instantiate (cloud) as GameObject;
for (int i = 0; i < secondRand; i++)
{
intPos = new Vector3 (Random.RandomRange(1, 4), 0, distance);
cloudInt.transform.position = intPos;
cloudInt.transform.Translate (distance, 0, 0);
distance -= 1;
}
}
if (firstRand == 2)
{
secondRand = Random.Range (1, 8);
for (int i = 0; i < secondRand; i++)
{
intPos = new Vector3 (Random.RandomRange(1, 4), 0, distance); }
GameObject enemyInt = Instantiate (enemy) as GameObject;
enemyInt.transform.position = intPos;
enemyInt.transform.Translate (distance, 0, 0);
distance -= 1;
}
}
}
}

Categories