Instantiate prefabs on endless runner top of previous one - c#

I am developing 2D Endless racer game, insted of constant background; i will use prefabs as background, i have 3 different prefabs as background: (Please Check Image)
Straight Road
Right Curved Road
Left Curved Road
I want to instantiate endless prefabs, according to instantiate point of each prefab,
I would appreciate for your support
Goal Image and Prefabs

One simple solution come straight from the example image you posted. Each road piece has its own "exit point", symbolized by that yellow circle. Since each road piece is its own prefab, you could give each of them an empty child object, acting like your yellow circle.
Each object would then have a reference to that object, and would use that to spawn the next object.
public class RoadPiece : Monobehaviour
{
public Transform nextInstantiatePoint;
To make the next road piece line up correctly, you could take advantage of the Sprite's Import Settings. Set the Pivot to "Bottom", or try the others for different effects.
The algorithm that you use to chose which piece to instantiate each time is up to you, but to start you could have an array of all the road pieces and pick one from there.
Ideally you want each object to wait some time before it instantiates the next, otherwise it will quickly cause the scene to be overcrowded. The easiest way to do it is like this:
void Start()
{
Invoke(nameof(SpawnNext), waitTime);
}
void SpawnNext()
{
Instantiate(roadPiece, nextInstantiatePoint.position, nextInstantiatePoint.rotation);
}
}

Related

How can I affect the transparency of many sprites at once through the parent GameObject?

I have a player that can move around a randomly generated map of rooms. I've been trying to figure out a way to keep all the rooms fully transparent/invisible, and then as soon as the player enters the room, that room becomes opaque.
I already have a way to detect the room the player is in, the main issue I'm having is changing the transparency of the room. Each room is made up of 30 or so "wall" tiles, which are just default square 2D sprites for now. These are the only thing I need to change the visibility of for now.
I saw that I can change the "material render value" or something similar to that per sprite, but I'm not sure of an easy way to do that for a whole lot of sprites at once that only have the default sprite renderer component and not a custom material.
Do I need to completely overhaul my rooms' walls to be one prefab for the whole wall? Or is there some way I could easily loop through each wall in a targeted room and change the transparency/visibility?
You could use the GameObject.SetActive(bool) it has the utility to disable and enable the visibility of the GameObject.
(I believe you have already done this, but if not) In your hierarchy you would first create an Empty and add your room to it, rename it with the name of your room and you could use the following script when detecting the room the player is in.
public GameObject room; //link your room here
void Start()
{
room.SetActive(false);
}
void Update()
{
//When detecting the room
room.SetActive(true);
}
The bool parameter of the SetActive() void sets whether the object is visible or not, when false it is invisible, and when true it is visible. I don't have your script as a reference, so I used an example
You should use GetChild() and for {}. Get child gets the child of the index you chose, and accesses it. Here is the script:
void Update()
{
for (int i = 0, i <= transform.childCount, i += 1)
{
GameObject child = GetChild(i);
// change the values here using child.GetComponent<>()
}
}
This is what the computer does: sets int i. Does this object have less children than the variable, i? Yes, run the code underneath. set child to the child of index i. i increases by 1. Repeat until i is greater than the child count.
Links:
https://docs.unity3d.com/ScriptReference/Transform.GetChild.html
https://www.w3schools.com/cs/cs_for_loop.asp

Destroying object at raycast 2D causes unrelated object to be destroyed

In my game the user can spawn instantiated versions of 2 prefabs with mouse clicks: tiles and balls. The balls can be spawned over the tiles.
The user can also erase objects which have been spawned. This is achieved by placing the following code in a if(Input.GetMouseButtonDown(0))) block of the update method:
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = canvas.transform.position.z;
Vector3 mousePosTrans = Camera.main.ScreenToWorldPoint(mousePos);
RaycastHit2D rayHit = Physics2D.Raycast(mousePosTrans, Vector2.zero);
if (eraserSelected)
{
Destroy(rayHit.collider.gameObject);
}
}
The objects intended for deletion are being deleted, but the problem is that other unrelated and distant objects are sometimes also simultaneously deleted. For example, if I spawn 2 squares and a ball on each square, then delete the first ball, when I go to delete the first square the second ball is simultaneously deleted. Sometimes when an object is deleted another object is simultaneously "un-deleted"!
Objects are spawned with the following code:
TileOrBall obj = (TileOrBall) Instantiate(tileOrBall, pos, Quaternion.identity);
obj.transform.SetParent(canvas.transform);
where TileOrBall is the class of the objects being spawned and tileOrBall is a reference to one of the two prefabs from this class.
So is there something wrong with the approach I'm taking to object spawning or destruction? How can I solve the simultaneous deletion (and sometimes resurrection) of distinct objects when trying to destroy an instance of these objects?
EDIT:
Adding link to zip file of project:
https://drive.google.com/open?id=0B28_MgFRWv97OWxfNE96LXcxZHc
To replicate the issue, click on the square in the side bar and "paint" squares in the grid wherever, then click on the ball in the side bar and "paint" over the squares that have been placed. Finally, click on the eraser icon and start deleting objects by clicking on them. You will see that objects you did not click on are deleted, and you may even see that objects are resurrected when you try deleting objects.
Thanks!
Found few problems in the Project.
1.When you do Destroy(unitAtMouse);, you are not deleting the GameObject from the raycast. You are ONLY deleting the Unit script that is attached to that GameObject.
Because this deletion failed, you will have multiple multiple Square GameObjects in one spot. That makes it harder to delete later on since you have to click delete multiple times until the last Square GameObjects is deleted.
To fix this, replace Destroy(unitAtMouse); with Destroy(unitAtMouse.gameObject);.
2.It is good to have the GameObject you are instantiating to be GameObject instead of script. For example public Unit selectedObject; should be public GameObject selectedObject;
3.Set eraserSelected to false when the square or circle in the side bar is clicked. This fixes problems that even user selects the square while again while in eraserSelected mode, they can delete or even create new square. You want to disable eraserSelected if square or circle in the side bar is clicked. In another word, if setSelectedObject is called.
4.The Erase Button should be under the panel like the other buttons too. Otherwise, it will go missing under some screen resolution.
5.Fixed enum to use the actual enum instead of enum.string.
6.Fix a problem that made the ball invisible which makes it look like it was deleted. What happens is that the ball is sent behind the square. Fixed this by making the ball sortingOrder to the 1 and the square sortingOrder to be 0.
Alternatively, building on #Programmer's response you could create a new script, say DeletableObject, that can be completely empty for the time being and attach this to the ball and square prefabs and any future prefabs you may have. Then in the suggested code above, change:
if (rayHit.collider.CompareTag("ball"))
to
if(rayHit.collider.GetComponent<DeletableObject>())
That way you can attach the script to any future prefabs you make to be able to delete them.
On a side note, if you're adding / deleting lots of objects and performance becomes an issue, look into Object Pooling. In fact, you should look into it anyway as it's a good habit to get into.

Changing Sprites using scripts in Unity2D C#

I am wanting to make a birds-eye view pixel-art game.
I currently have two sprite sheets set up, and split and whatnot
groundSheet and characterSheet these are split up into
ground_0_0_0 (A concrete floor)
ground_1_0_0 (grass)
character_0_0_0 (man idle animation frame 1)
character_0_0_1 (man idle animation frame 2)
character_0_1_0 (man run animation frame 1)
character_0_1_1 (man run animation frame 2)
character_1_0_0 (woman idle animation frame 1)
character_1_0_1 (woman idle animation frame 2)
character_1_1_0 (woman run animation frame 1)
character_1_1_1 (woman run animation frame 2)
The numbers after are a note as to:
first number - the main set of sprite animations (eg man)
second number - the animation set in use (eg run or idle)
third number - the frame of said animation.
(the ground has this as i plan to have animated grounds late on)
Now, I wish to make a script for the character (and ground alike) that has an editable value that is view able in the unity editor, for example how things like the sprite renderer has sprite, colour etc. Which dictates what first number to use (see above) what second number and the delay for the animation of the third number. This will then tell the sprite renderer what pictures to load and how quickly to load them. I also wish for the script to scan for the file starting with for example character_0_0_ and then count how many files after it, so it knows what to do when animating. I would like this script to be checking for a change in one of the variables viewable in the unity editor to change and as soon as it does it checks everything it needs for an animtion.
Something else could be done where there is only 1 box to edit in unity, which you put character_0_0_ or ground_1_0_ or something similar, and it checks everything that way (it also makes the script universal, and usable on the ground, character and walls (which I am adding later)).
This may seem confusing, but it make sense for me and many of you will probably mention a much easier way to do animations and such, but please only say these if it does what I want above.
For scripts and such my file layout:
/Assets
/scripts
ground.cs
character.cs
/sprites
characterSheet.png
character_0_0_0
character_0_0_1
character_0_1_0
character_0_1_1
character_1_0_0
character_1_0_1
character_1_1_0
character_1_1_1
groundSheet.png
ground_0_0_0
ground_1_0_0
(For some reason Stack overflow said the above was code, so i had to make it as that)
ground.cs and character.cs are the scripts in which I want to made as explained above.
In my object view thingy I have
Main Camera
ground
character
I am practically a newb to C# and JS I know bascially the grammar of C# (like where to use {} and put ; at the end of the lines). If you help me with this, i request that you explain the script, like use the // thing to simply explain what each command does, I know a few but not all of them. And I know someone is going to say it is really well documented in tutorial X and such, but most tutorials are not in unity 5 and while helping with the matter do not touch on it exactly.
Thank you for your help, if there is anything about this question/request that you do not understand (It is pretty complex) I will explain.
Maybe I am completely wrong, but it seems to me that you are trying to recreate an Animation system.
Is there a specific reason for which you wouldn't use Unity's animation system?
You can do everything that you describe here with it (change sprite, choose animation speed). And you would have almost no code to write. Just drag and drop you sprites in the editor for a start
EDIT - answer to first comment:
What you should do is create all the animations you need. Then in the animator, you choose which condition will trigger a transition to another animation (for instance, boolean jump is true will transition to animation jump). Then in your code you can call GetComponent().SetBool("Jump", true).
To have different character, you can create different gameObjects (one per character). They all have a different animator with animations specific to the character.
The other solutiojn if you really want one one gameObject and one animator is that you also add string condition to you animation (example, if character=="character1" and jump==true, transition to jump animation).
If I were you I would really focus on testing and learning all you can do with Unity animator. I can't think of a case were you would need to recreate the animation system yourself
Your question was long winded and hard to understand but ill try to help,
firstly if you want editable values in the unity editor I would Suggest using a serialized structure of information like this
[System.Serializable] // this makes it viewable in the inspector
public struct Sprite_Manager;
{
public Sprite[] Render_Sprites; // array of sprites to store sprites
public SpriteRenderer S_Renderer;
public float Anim_Delay;
}
public class Character : MonoBehavior {
Sprite_Manager SMG = new Sprite_Manager(); // instantiate a new instance of the struct
void Set_Sprite()
{
for(int i = 0; i < SMG.Render_Sprites.Length; i++)
{
SMG.S_Renderer.sprite = SMG.Render_Sprites[i];
}
}
void Update
{
Invoke("Set_Sprite", SMG.Anim_Delay);
}
}
Not sure if this is exactly what your looking for but this is one way you could setup a structure of sprite based information and use Invoke to setup some sort of delay when passing new sprites to the renderer.

Monogame - creating a player

after some fine-tuning on my game's GUI I am finally ready to begin with the gameplay. But that's a tall order. My game will be something like a 2D platformer with RPG elements like collecting armor, helmets, weapons etc. So with that in mind I begun thinking about a way to create my player. First, I thought a single Player class would do the job for me but since I want to equip the armor/helmet I've acquired, I quickly abandoned this concept.
Next I got another idea. I could have the player's Head, Arms and Legs to be different classes and each of them drawing its own texture, respectively. So I can swap between different armor/helmet sprites for each of the body parts. But that would seem pretty complex to implement... or not?
Could I have a code example on how you would do this? Which path you would take if you are in my stead? Single Player class or different body parts classes? If the latter, how would you hook them so that it all looks like a single sprite?
Armor/helmet should be part of the character status as it could be Health points. If you get hit your HP goes down and if your character collides with a helmet item then you should flag that status into your player object and render your character accordingly.
You may want to use the game component pattern (link is a very good read).
You probably want the player class still be the main base of the character, and have armor/clothing components that draw on top of the character.
The player class can then "have" the components and draw accordingly, add HP or other logic you like etc. A component could "break" and disappear etc.

Merge colliders of different gameobjects

I'm trying to create an auto spawned of game object out of predefined prefab.
The prefab contains a polygon collider.
The spawned instantiates the new object right at the end of the previous one, in a way that it looks like a single piece.
I'm trying to understand how to merge both of their colliders to be like a single polygon collider defined on the merged object.
Thank you for helping.
Btw if there's a code involved (which I'm sure there is), I would be glad if you could write it in c#.
Thank you!!
So from reading your Q and information provided i would say that you want one polygon collider to be exactly on the other. If this is your goal, when they collide, you can us the transform function and move it to the exact position of the other.

Categories

Resources