Spawn sprites on action - unity3d

I'm trying to make a Pinata GameObject, that when clicked bursts and gives a variable number of Gift GameObjects with various images and behaviors in them.
I'm also not sure what the unity vocabulary for this is so as to look this up in unity docs.
Can anyone please lend me a hand here? Thanks!

There are several ways to handle this.
The simple way is to use Object.Instantiate, Object Instantiation is the vocab you're after.
This will create a copy of a predefined Unity object, this can be a gameobject or any other object derived from UnityEngine.Object, check the docs for more info https://docs.unity3d.com/ScriptReference/Object.Instantiate.html.
In your case, your Pinata would have an array, or list, of prefabs. These prefabs are created by you with a certain behaviour and sprite for each one. When the Pinata bursts, you instantiate random prefabs at random positions surrounding the Pinata, up to you how to position these objects.
Something along these lines should do the trick:
class Pinata : Monobehaviour
{
public GameObject[] pickupPrefabs;
public int numberOfItemsToSpawn; //This can be random
//any other variables that influence spawning
//Other methods
public void Burst()
{
for(int i = 0; i < numberOfItemsToSpawn; i++)
{
//Length - 1 because the range is inclusive, may return
//the length of the array otherwise, and throw exceptions
int randomItem = Random.Range(0, pickupPrefabs.Length - 1);
GameObject pickup = (GameObject)Instantiate(pickupPrefabs[randomItem]);
pickup.transform.position = transform.position;
//the position can be randomised, you can also do other cool effects like apply an explosive force or something
}
}
}
Bare in mind, if you want the game to be consistent, then each behaviour prefab would have there own predefined sprite, this would not be randomised. The only thing randomised would be the spawning and positioning.
If you did want to randomise the sprites for the behaviours then you'd have to add this to the Pinata class:
public class Pinata : Monobehaviour
{
//An array of all possible sprites
public Sprite[] objectSprites;
public void Burst()
{
//the stuff I mentioned earlier
int randomSprite = Random.Range(0, objectSprites.Length - 1);
SpriteRenderer renderer = pickup.GetComponent<SpriteRenderer>();
//Set the sprite of the renderer to a random one
renderer.sprite = objectSprites[randomSprite];
float flip = Random.value;
//not essential, but can make it more random
if(flip > 0.5)
{
renderer.flipX = true;
}
}
}
You can use Unity random for all your random needs, https://docs.unity3d.com/ScriptReference/Random.html
Hopefully this'll lead you in the right direction.

Related

Instatiated objects from the same prefab share a position?

I'm starting a simple JRPG: generating a party from a group of prefabs, then moving each into position by changing their transform. But seeing a strange one where 3 goblins spawned from the same prefab are moving to exactly the same position. The other objects instantiated from different objects are moving correctly.
In the player, I can move the goblins by changing their transform, and they are separate. However the prefab itself is changing position to match the 'last' goblin spawned
Any hints? Am I somehow instantiating them to a common object?
Objects created and positioned in PartyManager:
public bool playerParty = true;
public GameObject[] party=new GameObject[4];
// Start is called before the first frame update
void Start()
{
for (int i=0; i<party.Length; i++){
GameObject character = Instantiate(party[i],this.gameObject.transform);
}
positionCharacters();
}
void positionCharacters(){
float facing = -1.0f;
if(playerParty) facing=1.0f;
for (int i=0; i<party.Length; i++){
party[i].transform.localPosition = new Vector3(-0.3f*i*facing, -0.05f*i,-0.1f*i);
print(party[i]+" moved to "+party[i].transform.localPosition);
}
}
First of all you don't seem to be storing references to the instantiated characters, GameObject character just goes out of scope immediately. If you put three references to the same object into GameObject[] party you shouldn't be surprised only the last set position is used.

Best way to create a 2d top down race track procedurally

I am attempting to create a 2d top-down car racing game. This game will have a random road map each time the player plays the game. I have thought about doing this in two different ways: A tilemap, or just generate the roads by placing different prefabs (straight roads, turns, etc). I have decided to go with the prefab route.
The way I believe it should work is to have prefab square "tiles" which have their own colliders set on the edges so I can tell if a player goes off the track in which case they blow up. I would have a MapGenerator Script which will generate an initial random map by keeping track of the last tile placed (including its location and road type: left turn, straight, right, etc). This script will then keep adding onto the road randomly as the player gets closer and closer to the end which makes it an infinite road.
I just want to know if this is just not efficient or if I am thinking of this completely wrong.
Here are a couple of images showing my road tiles which I made in photoshop and then one prefab for a straight road (take note of the colliders on its edges).
A similar game to one I want to make is Sling Drift which I can provide the link if you want. I don't know the policy on adding links to forum chat.
Also, here is my code for the map generator:
//Type of tyle, types are normal (straight road or horizontal road) and turns
public enum MapTileType
{
NORMAL,
N_E,
N_W,
S_E,
S_W
}
//structure for holding the last tile location and its type.
public struct TypedTileLocation
{
public TypedTileLocation(Vector2 pos, MapTileType tyleType)
{
m_tileType = tyleType;
m_position = pos;
}
public Vector2 m_position;
public MapTileType m_tileType;
}
public class MapGenerator : MonoBehaviour
{
//Map Tiles
public GameObject m_roadTile;
public GameObject m_turnNorthWestTile;
//holds all the tiles made in the game
private List<GameObject> m_allTiles;
//Map Tile Widths and Height
private float m_roadTileWidth, m_roadTileHeight;
//Used for generating next tile
TypedTileLocation m_lastTilePlaced;
private void Awake()
{
//store the initial beginning tile location (0,0)
m_lastTilePlaced = new TypedTileLocation(new Vector2(0,0), MapTileType.NORMAL);
//set height and width of tiles
m_roadTileWidth = m_roadTile.GetComponent<Renderer>().bounds.size.x;
m_roadTileHeight = m_roadTile.GetComponent<Renderer>().bounds.size.y;
m_allTiles = new List<GameObject>();
}
// Start is called before the first frame update
void Start()
{
SetupMap();
}
void SetupMap()
{
//starting at the beginning, just put a few tiles in straight before any turns occur
for (int i = 0; i < 6; ++i)
{
GameObject newTempTile = Instantiate(m_roadTile, new Vector2(0, m_roadTileHeight * i), Quaternion.identity);
m_lastTilePlaced.m_tileType = MapTileType.NORMAL;
m_lastTilePlaced.m_position.x = newTempTile.transform.position.x;
m_lastTilePlaced.m_position.y = newTempTile.transform.position.y;
m_allTiles.Add(newTempTile);
}
//now lets create a starter map of 100 road tiles (including turns and straigt-aways)
for (int i = 0; i < 100; ++i)
{
//first check if its time to create a turn. Maybe I'll randomly choose to either create a turn or not here
//draw either turn or straight road, if the tile was a turn decide which direction we are now going (N, W, E, S).
//this helps us determine which turns we can take next
//repeat this process.
}
}
void GenerateMoreMap()
{
//this will generate more map onto the already existing road and then will delete some of the others
}
// Update is called once per frame
void Update()
{
}
private void OnDrawGizmos()
{
}
}
Thanks!
Have you tried splines? They let you make curvy paths like race tracks easily. If not, here is a video that might help: https://www.youtube.com/watch?v=7j_BNf9s0jM.

Instantiate GameObjects and change Material when it hits on the ground

There is a code for instantiate cube into the list and change a Material of each clone when it hits on the ground
The following code works but not in Real-Time. Update function works like a Start function for a Foreach method
How to get a value of item.transform.position.y in the Update function Real-Time?
public GameObject cubePrefab;
public Material RedMat;
public float GroudLevel = 0.5f;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
List<GameObject> cloneList = new List<GameObject>();
//instantiate clones into the list
for (int i = 0; i < 10; i++)
{
var clone = Instantiate (cubePrefab,new Vector3(Random.Range(-3f, 3f),
Random.Range(4f, 10.5f),Random.Range(-3f, 3f)), Quaternion.identity);
cloneList.Add(clone);
}
//if clone is grounded change a Material for each clone
foreach (var item in cloneList)
{
//Debug.Log(item.transform.position.y);
//check if clone is on the ground
if(item.transform.position.y < GroudLevel)
{
item.GetComponent<Renderer>().material = RedMat;
}
}
}
}
There is a screenshot for a GroudLevel = 7
The reason this function isn't working is because the pivot (transform.position) of your item is always in the center of the object. This isn't something you can change in Unity (nor would you necessarily want to).
On top of this, you're checking if the item is under the ground, and not on it when you use < insteaad of <=, because the position needs to be less than groundLevel to return true.
There are several solutions here.
The simplest would involve moving all of this logic to an OnCollisionEnter or OnTriggerEnter method. For more information on this, check the Unity documentation.
Another solution would be to find a way tthe size of the object, divide it by two, and check if
item.transform.position - halfSize <= groundLevel;
This seems really cumbersome and overly complex, however. You'd be better off using Unity's built-in collision system, unless you have a reason not to.

Why Does My Mesh Combiner Script Make Child Objects Invisible And Change Their Placements?

To further optimize my game, I wanted to combine the meshes of the hallways so that the frame rate would be higher. the code is intended to take all of the children inside of an empty game object(titled walls, floors, etc.) and combine their meshes into one. However, whenever I ran the script, all of the child objects would appear in completely random positions and were invisible. How can I make so that the objects all appeared at their original position and were visible?
How I set up the code is that I would place any repeated objects in an empty gameObject to easily categorize them (titled as Walls, Floors). Afterwards, I would assign the script to the empty gameObject and expect every repeated object in the empty gameObject to combine.
Here's an example:
Here's The Code:
using UnityEngine;
using System.Collections;
// Copy meshes from children into the parent's Mesh.
// CombineInstance stores the list of meshes. These are combined
// and assigned to the attached Mesh.
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class CombineMesh : MonoBehaviour
{
void Update()
{
if(Input.GetKeyDown(KeyCode.J))
{
CombineMeshes();
}
}
void CombineMeshes()
{
Quaternion oldRot = transform.rotation;
Vector3 oldPos = transform.position;
transform.rotation = Quaternion.identity;
transform.position = Vector3.zero;
MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>();
CombineInstance[] combine = new CombineInstance[meshFilters.Length];
int i = 0;
while (i < meshFilters.Length)
{
combine[i].mesh = meshFilters[i].sharedMesh;
combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
meshFilters[i].gameObject.SetActive(false);
i++;
}
var MeshFilter = transform.GetComponentInChildren<MeshFilter>();
MeshFilter.mesh = new Mesh();
MeshFilter.mesh.CombineMeshes(combine);
GetComponentInChildren<MeshCollider>().sharedMesh = MeshFilter.mesh;
transform.gameObject.SetActive(true);
transform.rotation = oldRot;
transform.position = oldPos;
}
}
Answering late in case anyone happens to be searching for this information.
Unity's documentation is uncharacteristically unhelpful, as is the internet in general.
Lengthy Explanation
Kayra's Code Corrected
Working Code: Helper Functions
Working Code: CombineMeshes
Lengthy Explanation:
Two things to keep in mind are
Meshes are defined via a Vector3[](see meshFilter.mesh.vertices), describing the coordinates of each vertex relative to its meshFilter's transform (so local space). This is very important later on.
There is no black magic involved - math is not black magic ;)
First, you should understand "transform.localToWorldMatrix" and "transform.worldToLocalMatrix"
These are very misleading names - all these Matrix4x4 actually do in Unity, is describe the linear transformation between
{position: Vector3.zero, rotation: Quaternion.identity, scale: Vector3.one} and
the given transform's {position, rotation, scale}.
Its telling you by how much to move in which direction, by how much to rotate in which direction, and by how much to scale.
In fact: transform.localToWorldMatrix == transform.worldToLocalMatrix.inverse -- they're the exact same thing, just flipped around.
See "Khan Academy" or "3blue1brown" on YouTube for great explanations of Linear Transformation
We usually don't use Matrices in Unity, because we can access/modify the position, rotation, and scale directly -- for us, it's just a different way of storing the same information.
I wrote some working code to visualise what's actually happening in Unity:
/// Demonstration of how transform.localToWorldMatrix works - very important for understanding CombineInstance.transform
/// Place two 3D objects in your scene, attach this script somewhere, and assign the 3D Objects to the public variables
/// This script will auto-run inside a coroutine 2 seconds after Start(), because I use the InputSystem package and maybe you still use if(Input.getKeyDown()).
/// It's the easiest way I know of to guarantee working code in your scene
public class StackOverflowExample : MonoBehaviour
{
public Transform parent;
public Transform child;
private IEnumerator exampleMethod;
/// <summary>
/// Just setting some conditions, in case you try out this code
/// </summary>
private void Start()
{
parent.position = new Vector3(5f, 0f, 3f);
child.parent = parent;
child.localPosition = new Vector3(2f, 0f, 2f);
//Only doing this because I use the InputSystem package, and others maybe don't (yet...)
exampleMethod = TransformMatrixExample();
StartCoroutine(exampleMethod);
}
//Only doing this because I use the InputSystem package, and others maybe don't (yet...)
private IEnumerator TransformMatrixExample()
{
//wait for 2 seconds just because...
yield return new WaitForSeconds(2f);
//parent.position = parent.position - parent.localToWorldMatrix.GetPosition();
// Commented out on purpose. Would result in 0,0,0 parent.position, because parent has no gameObject parent...
//and therefore break the demonstration:
child.position = child.position - parent.localToWorldMatrix.GetPosition();
// child.localPosition (see the inspector) now states (-3f,0f,-1f)
// however, child.Position (just unparent the gameObject in the inspector) is now (2f,0f,2f)
}
}
When you tell each CombineInstance what Matrix4x4 to use in
combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
you are describing by how much to offset each soon-to-be-combined mesh's vertices' coordinates before combining it.
Once again, we usually access/modify the position, rotation, and scale directly - Mesh.CombineMeshes() uses a 4x4 matrix.
Here Matrix4x4.GetPosition() returns the vector leading from Vector3.zero to parent.position - which is contained inside that matrix
We are effectively moving the child object to the place it would be if the parent were at coordinates (0f,0f,0f).
The same thing happens with rotation and scale.
In the while-loop in your code, there's a statement:
combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
The problem with this is that if the parent object (or the mesh you want to merge into) is not positioned at Vector3.zero, all the meshes will still pretend otherwise and offset themselves by the wrong amount. That is why you have to move the parent.transform.position to vector3.zero before assigning to the CombineInstances[].
So in my code example above:
parent.position = new Vector3(5f, 0f, 3f);
child.localPosition = new Vector3(2f, 0f, 2f);
If I first move the parent to V3.zero, the results given by transform.localToWorldMatrix.GetDistance():
combine[i].transform = meshFilters[i].transform.localToWorldMatrix :
parent's offset: V3(0f,0f,0f) --> parent.position
child's offset: V3(2f,0f,2f) --> child.position
This works because now, the vector from child.position to V3.zero == vector from child.position to parent.position.
If I were to use the transforms without first moving the parent to V3.zero, I would get the following results:
combine[i].transform = meshFilters[i].transform.localToWorldMatrix :
parent's offset: V3(5f, 0f, 3f) --> parent.position
child's offset: V3(7f, 0f, 5f) --> parent.position + child.localPosition
Because transform.localToWorldMatrix returns the vector from zero to that transform.position.
Remember Point1 of things to remember?
Vertex coordinates are defined in local space relative to their meshFilter's transform.
In other words:
all of parent mesh's vertices will offset by an additional V3(5f,0f,3f) --> parent.position
all of child mesh's vertices will be offset by an additional V3(7f,0f,5f) --> parent.position + child.localPosition
The statement is effectivley telling Unity the following (pseudocode):
foreach (Vector3 v in meshFilters[i].mesh.vertices)
{
v += meshFilters[i].localToWorldMatrix.GetPosition();
//and now append my vertex to the new MeshFilter's mesh...
//in other workds: Pretend that my parent is at 0,0,0 and I'm in the right spot already
}
The exact same principle holds true for rotation and scale. You can probably decipher that from the working code later on.
kayra yorulmaz's Corrected Code
I'm assuming that CombineMesh.cs is attached to the "Floors" gameObject,
and that "Floors" transform.rotation = (0f,0f,0f).
The Quaternion operations will be explained shortly.
So the kayra yorulmaz's code would have to be written as follows:
using UnityEngine;
// Copy meshes from children into the parent's Mesh.
// CombineInstance stores the list of meshes. These are combined
// and assigned to the attached Mesh.
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshCollider))] //because otherwise line 72 might throw an exception...
public class CombineMesh_Corrected : MonoBehaviour
{
void Update()
{
if(Input.GetKeyDown(KeyCode.J))
{
CombineMeshes();
}
}
void CombineMeshes()
{
Vector3 transformOffset = transform.position;
MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>();
CombineInstance[] combine = new CombineInstance[meshFilters.Length];
int i = 0;
while (i < meshFilters.Length)
{
Quaternion rotationOffset = Quaternion.FromToRotation(transform.eulerAngles, meshFilters[i].transform.eulerAngles);
meshFilters[i].transform.position -= transformOffset;
meshFilters[i].transform.rotation = Quaternion.Euler(meshFilters[i].transform.eulerAngles) * Quaternion.Inverse(rotationOffset);
combine[i].mesh = meshFilters[i].sharedMesh;
combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
meshFilters[i].gameObject.SetActive(false);
//we already stored the 4x4Matrix in combine[i].transform, so it's safe to change back now
meshFilters[i].transform.position += transformOffset;
meshFilters[i].transform.rotation *= rotationOffset;
i++;
}
MeshFilter meshFilter = transform.GetComponent<MeshFilter>();
meshFilter.mesh = new Mesh();
meshFilter.mesh.CombineMeshes(combine);
GetComponentInChildren<MeshCollider>().sharedMesh = meshFilter.mesh;
transform.gameObject.SetActive(true);
}
}
Working Code Example
However, it you create your own Matrix4x4 to describe the necessary linear transformation, you don't have to touch the gameObject's transforms at all.
Remember that Vertices (and therefore the meshes you're combining) are described relative to the meshFilter's transform.
So if we create a Matrix4x4 for each child meshFilter, describing how that child.meshFilter.transform is located relative to parent.meshFilter.transform, we can tell Unity where to place the vertices for the combined mesh:
So here's is the code based off what I just wrote for my own project.
Necessary Helping Functions
using UnityEngine;
public static class StackoverflowHelpers
{
/// <summary>
/// Returns the difference between quaterions, treated as local rotations because of the order...
/// https://answers.unity.com/questions/810579/quaternion-multiplication-order.html
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <returns></returns>
public static Quaternion FromTo(Quaternion from, Quaternion to)
{
return Quaternion.Inverse(from) * to;
}
public static Quaternion Add(Quaternion start, Quaternion difference)
{
return start * difference;
}
public static Quaternion Subtract(Quaternion start, Quaternion difference)
{
return start * Quaternion.Inverse(difference);
}
public static Vector3 RatioBetween( Vector3 fromScale, Vector3 toScale)
{
return new Vector3(
toScale.x/fromScale.x,
toScale.y/fromScale.y,
toScale.z/fromScale.z );
}
}
Actual CombineMesh Method
using System.Collections.Generic;
using UnityEngine;
public static class StackOverflow_CombineMesh
{
public static void Simple(List<MeshFilter> _meshFilters, bool _deleteOriginals = true)
{
CombineInstance[] combineInstances = new CombineInstance[_meshFilters.Count];
Transform parent = _meshFilters[0].transform;
for (int i = 0; i < _meshFilters.Count; i++)
{
/// set up the matrix describing the step from the parent mesh to the child mesh
Transform child = _meshFilters[i].transform;
Vector3 posOffset = child.position - parent.position;
posOffset.x *= 1/parent.localScale.x;
posOffset.y *= 1/parent.localScale.y;
posOffset.z *= 1/parent.localScale.z;
Matrix4x4 ParentToChildMatrix = Matrix4x4.TRS(
posOffset,
StackoverflowHelpers.FromTo(parent.rotation, child.rotation),
StackoverflowHelpers.RatioBetween(parent.lossyScale, child.lossyScale));
combineInstances[i].mesh = _meshFilters[i].mesh;
combineInstances[i].transform = ParentToChildMatrix;
child.gameObject.SetActive(false);
}
_meshFilters[0].mesh = new Mesh();
_meshFilters[0].mesh.CombineMeshes(combineInstances, true, true);
_meshFilters[0].gameObject.SetActive(true);
}
Bear in mind that meshes in unity have a maximum number of vertices (65,535 to be exact) - if you cross that limit your mesh won't render properly after all.
Have fun, keep learning!
Gecko
I think this is a common issue with Unity mesh combine, try changing this line (assuming this is all on the Parent game object):
combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
to this:
combine[i].transform = meshFilters[i].transform.localToWorldMatrix * transform.worldToLocalMatrix
where transform.worldToLocalMatrix is the parent object. You could also try something like:
combine[i].transform = meshFilters[i].transform.localToWorldMatrix * meshFilters[i].transform.parent.transform.worldToLocalMatrix;
Depends on how you have it set up

how to randomly initialize particles system in different places of scene in unity3d

I recently tried asking this question but I realized it was not a sufficient question. In my game the player is a fire fighter learner and i want to broke out fire randomly in my game (like not predictable by player), but i did not know how to implement this.
So far i have done this but nothing goes good.(I have a empty object called t in unity which have 3 to 5 particles systems, and all are set to dont awake at start)
code is here :
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
public ParticleSystem[] particles;
public int numOn = 3;
public int j;
void Start() {
for (int i = 0; i < particles.Length - 1; i++) {
j = Random.Range(i + 1, particles.Length - 1);
ParticleSystem t = particles[j];
particles[j] = particles[i];
particles[i] = t;
}
for (j = 0; j < numOn; j++ )
{
particles[j].Play();
}
}
}
help will be appreciated :-)
You could try using prefabs. Create a game object in the editor that has any particle systems and scripts your fire objects need. Once it's good, drag the object from the hierarchy into your project. This will create a prefab (you can now remove it from the scene). Now, on your spawning script, add a field of type GameObject and drag the prefab you made before into it. Now, when you need to create one, just call Instantiate(prefabVar) to create a copy of your prefab.
Edit:
For your specific case, since you only want one fire to be instantiated in a random location, you could have your spawning script look something like this:
public Transform[] SpawnPoints;
public GameObject FirePrefab;
void Start() {
Transform selectedSpawnPoint = SpawnPoints[(int)Random.Range(0, SpawnPoints.Count - 1)];
Instantiate(FirePrefab, selectedSpawnPoint.position, selectedSpawnPoint.rotation);
}
This solution would allow for you to potentially spawn more than one fire object if you needed. An alternative would be if you will only ever have exactly one fire object in the scene at all. Instead of instantiating from a prefab, the object is already in the scene and you just move it to one of your spawn points at the start of the scene. An example script on the fire object itself:
public Transform[] SpawnPoints;
void Start() {
Transform selectedSpawnPoint = SpawnPoints[(int)Random.Range(0, SpawnPoints.Count - 1)];
transform.position = selectedSpawnPoint.position;
transform.rotation = selectedSpawnPoint.rotation;
}