How to generate ground in unity2d endless runner - c#

I currently write a game, and I have 2 scripts that generate the ground in the game. However, instead of generating them as the player comes to the end of one ground, they're generated as soon as the game starts. I don't want this to happen.
Does someone know why it happens?
Please help me fix this.
Thanks!
This is my code:
Script 1:
public class ObjectPooler : MonoBehaviour
{
public GameObject pooledObject;
public int pooledamnt;
List<GameObject> pooledObjects;
// Start is called before the first frame update
void Start()
{
pooledObjects = new List<GameObject>();
for (int i = 0; i < pooledamnt; i++)
{
GameObject obj = (GameObject)Instantiate(pooledObject);
obj.SetActive(false);
pooledObjects.Add(obj);
}
}
public GameObject GetPooledObject()
{
for (int i = 0; i < pooledObjects.Count; i++)
{
if (pooledObjects[i].activeInHierarchy)
{
return pooledObjects[i];
}
}
GameObject obj = (GameObject)Instantiate(pooledObject);
obj.SetActive(false);
pooledObjects.Add(obj);
return obj;
}
// Update is called once per frame
void Update()
{
}
}
Script 2:
public class
GroundGenerator : MonoBehaviour
{
public GameObject thePlatform;
public Transform GenOnPoint;
public float DistanceBetween;
private float PlatformWidth;
public float DistanceBewtweenmin;
public float Di stanceBetweenmax;
public ObjectPooler objectpool;
public GameObject[] thePlatforms;
private int platformSelecter;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
GameObject newPlatform = objectpool.GetPooledObject();
newPlatform.transform.position = transform.position;
newPlatform.transform.rotation = transform.rotation;
newPlatform.SetActive(true);
}
}

Here is a basic script to generate ground as the player moves :
using UnityEngine;
public class GroundGeneration : MonoBehaviour
{
public float ClosestDistacnceFromPlayer;
public GameObject GroundTile;
public float TileWidth;
public Transform Player;
void Start()
{
//Spawn a tile so that the player won't fall off at the start
SpawnTile(1);
}
void SpawnTile(int n)
{
int i = 0;
//Spawn n tiles
while (i < n)
{
Instantiate(GroundTile, transform.position, Quaternion.identity);
i++;
//Teleport the "Ground generator" to the end of the tile spawned
transform.position += TileWidth * Vector3.right; // Or use Vector3.forward if you want to generate ground on z axis.
}
}
void FixedUpdate()
{
if (Vector3.Distance(Player.position, transform.position) <= ClosestDistacnceFromPlayer)
{
SpawnTile(1);
}
}
}
The GroundTile should have its origin at the point where it meets with the previous tile and it should be a prefab.
The Ground will start generating at the position of the object containing the ground generation script.

Related

Score board moves with Character movement in Unity C#

I have a C# script which is for a game in unity. When I run the scene, the Player/ character moves with the score board (want the score board not to move, for obvious reasons). I had a issue with Nullref error before, but fixed that and now the score board is an issue. All objects were imported/ created in the Assets folder and dragged to the world scene/ main scene.
Here's the code:
public class Script : MonoBehaviour
{
public AudioClip collectCoins;
public AudioSource audioSource;
public Text _mytext;
int i = 0;
private void Start()
{
}
public void OnCollisionEnter(Collision collision)
{
if (collision.collider.CompareTag("coin"))
{
i += 10;
audioSource.PlayOneShot(collectCoins);
Destroy(collision.gameObject);
}
if (collision.collider.CompareTag("coin2"))
{
i -= 10;
if (i < 0)
{
i = 0;
}
audioSource.PlayOneShot(collectCoins);
Destroy(collision.gameObject);
}
}
private void FixedUpdate()
{
}
float speed =0.2f;
void Update()
{
if(_mytext != null)
{
_mytext.text = "Bonus: " + i;
}
float move = Input.GetAxis("Horizontal") * speed;
transform.Translate(move, 0, 0);
}
}
Its the strangest thing...Tried everything...any ideas to what I should do? (appreciate any replies).

Updating Enemy Health bar in unity 2d

Why is this connecting all the health bars of my enemies together, even though their actual health is decreasing at its specified rate?
public class FillHealth : MonoBehaviour
{
Image HealthBar;
private NormalMonster normalMonster;
// Start is called before the first frame update
void Start()
{
HealthBar = GetComponent<Image>();
normalMonster = GameObject.FindGameObjectWithTag("Normal Monster").GetComponent<NormalMonster>();
}
// Update is called once per frame
void Update()
{
UpdateHealthLeft();
}
public void UpdateHealthLeft()
{
if (normalMonster.healthLeft > 0)
{
HealthBar.fillAmount = normalMonster.healthLeft / normalMonster.setHealth;
}
}
}
This is the script that is being referenced in FillHealth. As far as I understand it, since the variable isn't static, then the values should not be shared. It should find fill the health bar for each individual enemy.
public class NormalMonster : MonoBehaviour
{
private float _normalSpeed = 2f;
private float _BaseHealth = 20f;
private float _HealthModifier;
public float setHealth;
public float healthLeft;
// Start is called before the first frame update
void Start()
{
UpdateHealth();
}
// Update is called once per frame
void Update()
{
NormMonMov();
}
public void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Arrows")
{
healthLeft -= Arrows.Damage;
Destroy(other.gameObject);
if (healthLeft <= 0f)
{
Destroy(this.gameObject);
EarnedGold.earnedGold += 7;
Spawn_Manager.enemyCount--;
}
}
}
public void UpdateHealth()
{
if (StageMode.StageLvl > 5)
{
_HealthModifier = (StageMode.StageLvl * 0.01f) * _BaseHealth;
setHealth = Mathf.Round(_BaseHealth + _HealthModifier);
}
else
{
setHealth = _BaseHealth;
}
healthLeft = setHealth;
}
public void NormMonMov()
{
transform.Translate(Vector3.left * _normalSpeed * Time.deltaTime);
transform.position = new Vector3(Mathf.Clamp(transform.position.x, -7.0f, 10), transform.position.y, 0);
}
}
Any help would be greatly appreciated for this guy who just start playing with unity this weekend.
I believe the issue is with normalMonster = GameObject.FindGameObjectWithTag("Normal Monster").GetComponent<NormalMonster>();
If you have two Monsters
Both have two scripts attached, FillHealth and NormalMonster
Both the "FillHealth" scripts look for the FIRST gameobject in the scene that has a script with tag NormalMonster so both monsters are pointing to the exact same NormalMonster script (the first in the list)
Change "GameObject" capital G to "gameObject" lower case g
Still not the best way to code this, but that may work I think
Instead of getting the image, get the rect transform, like this
public RectTransform healthBar;
and change the length with:
healthBar.sizeDelta = new Vector2(normalMonster.healthLeft,healthBar.sizeDelta.y);

Unity-Breakout Game with a Healthbar

I'm making a breakout game, and I wanted to add a healthbar that decreases when the ball touches a certain object with the tag "hazard". I have a Game Manager Script, and A Pickup interact script, but with the way I set it up, I'm kind of confused with how to trigger takedamage from my GM script to my pickup script, considering I put my playerhealth elements into my GM script, so I can attach it to empty gameobject call Game Manager, since the actual player isnt in the hierarchy, but instantiated during runtime. I'm hoping I don't have to redo the whole thing just for this purpose. If someone could help me figure this out, I'd appreciate it.
Here's my GM script:
public class GM : MonoBehaviour
{
public int lives = 3;
public int bricks = 20;
public float resetDelay = 1f;
public Text livesText;
public GameObject gameOver;
private GameObject clonePaddle;
public GameObject youWon;
public GameObject bricksPrefab;
public GameObject paddle;
public GameObject deathParticles;
public static GM instance = null;
public int startingHealth = 100;
public int currentHealth;
public Slider healthSlider;
bool isDead;
bool damaged;
void Awake()
{
currentHealth = startingHealth;
TakeDamage(10);
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
Setup();
}
public void TakeDamage(int amount)
{
damaged = true;
currentHealth -= amount;
healthSlider.value = currentHealth;
if (currentHealth <= 0)
{
LoseLife();
}
}
public void Setup()
{
clonePaddle = Instantiate(paddle, transform.position, Quaternion.identity) as GameObject;
Instantiate(bricksPrefab, transform.position, Quaternion.identity);
}
void CheckGameOver()
{
if (bricks < 1)
{
youWon.SetActive(true);
Time.timeScale = .25f;
Invoke("Reset", resetDelay);
}
if (lives < 1)
{
gameOver.SetActive(true);
Time.timeScale = .25f;
Invoke("Reset", resetDelay);
}
}
void Reset()
{
Time.timeScale = 1f;
Application.LoadLevel(Application.loadedLevel);
}
public void LoseLife()
{
lives--;
livesText.text = "Lives: " + lives;
Instantiate(deathParticles, clonePaddle.transform.position, Quaternion.identity);
Destroy(clonePaddle);
Invoke("SetupPaddle", resetDelay);
CheckGameOver();
}
void SetupPaddle()
{
clonePaddle = Instantiate(paddle, transform.position, Quaternion.identity) as GameObject;
}
public void DestroyBrick()
{
bricks--;
CheckGameOver();
}
}
And here's my Pickup Script:
public class Pickups : MonoBehaviour {
public float PaddleSpeedValue = 0.5f;
private bool isActive = false;
public float thrust=20f;
public Rigidbody rb;
GameObject player;
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Hazard")
{
isActive = true;
Destroy(other.gameObject);
}
}
}
The Pickups class should not have or store a reference to the player at all (although it is not clear from your question if this is a script attached to the player or attached to something else). Your Game Manager class should. Afterall, it is the class that is responsible for managing the game which includes the player. From there, you can use GetComponent<?>() to access any scripts attached to the player GameObject.
Then as the GM contains a public static reference to itself, any other class can get a reference to the player by doing GM.instance.player as needed, even if the player is created and destroyed several times (as the GM should always have a reference to the current one!)
Presumably the clonePaddle field is the player('s GameObject), all you have to do is make it public.

Unity How to remove gameobject if they are on same line?

I am making a game like 2 cars. And I have written code to create a instantiater. It is a car game and there are 4 lanes. Let me show you a picture of my game and yeah this is solely for practise.
Player should avoid square objects and eat circle objects but sometimes 2 square objects get spawned in a same lane making impossible for player to win. I have written this script to control that but I failed. Please help me. At least have a check to my DetectSameLaneFunction(). And tell me what I am doing wrong.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour {
public GameObject[] objects;
public float delaytime = 2f; // this is separate for each prefab with which script is attaches
public float spawnrate = 1f; // this is separate for each prefab with which script is attaches
public static int lastgameobjectindex;
public static GameObject lastgameobject;
public static GameObject SecondLastGameObject;
private float loadingtime;
private GameObject go; // just a temporary variable
public static List<GameObject> spawnobjects = new List<GameObject>();
// Use this for initialization
void Start () {
loadingtime = delaytime;
}
// Update is called once per frame
void Update () {
if (Time.time > loadingtime)
{
float randomness = spawnrate * Time.deltaTime;
if ( randomness < Random.value)
{
Spawners();
}
NextLoadTime();
}
}
private void Spawners()
{
int spawnnumber = Random.Range(0, 2);
GameObject go = Instantiate(objects[spawnnumber]) as GameObject;
go.transform.position = this.transform.position;
spawnobjects.Add(go);
Debug.Log(spawnobjects[spawnobjects.Count-1]);
DetectSameLaneObjects();
/* if (spawnobjects.Count > 4)
{
spawnobjects.RemoveAt(0);
}*/
}
private void DetectSameLaneObjects()
{
if (spawnobjects.Count > 3)
{
lastgameobject = spawnobjects[spawnobjects.Count - 1];
SecondLastGameObject = spawnobjects[spawnobjects.Count - 2];
lastgameobjectindex = spawnobjects.Count - 1;
if (SecondLastGameObject.transform.position.x != lastgameobject.transform.position.x
)
{
if (Mathf.Abs(lastgameobject.transform.position.x- SecondLastGameObject.transform.position.x) < 2.3f)
{
Debug.Log("Destroy function getting called");
Destroy(spawnobjects[lastgameobjectindex]);
spawnobjects.RemoveAt(lastgameobjectindex);
}
}
}
}
void OnDrawGizmos()
{
Gizmos.DrawWireSphere(this.transform.position, 0.6f);
}
void NextLoadTime()
{
loadingtime = Time.time + delaytime;
}
}

Enemy life and bullet power unity3d c#

I am new at Unity. I have successfully made a player can shoot a bullet to the enemy depends on the current wave, and I make where the enemy have it is own life depends on the current wave multiply with certain value. If the enemy life is 0, the enemy dies. But, the problem is: for example there are 2 enemies on the scene and the enemy life is 5 and the player start shooting the first enemy until the enemy life decreases to 2, when the player start shooting the second enemy, the enemy life is not 5 anymore, but it is 2 until one of the 2 cubes is dead and the enemy life reset to 5.
How can I solve this problem?
Here is the bullet script:
public class BulletManager : MonoBehaviour
{
private ScoreManager scoreManager;
private PlayerController playerController;
private EnemyManager enemyManager;
public int bulletPower;
private void Start()
{
scoreManager = GameObject.Find("Game Manager").GetComponent<ScoreManager>();
playerController = GameObject.Find("Character").GetComponent<PlayerController>();
enemyManager = GameObject.Find("Game Manager").GetComponent<EnemyManager>();
bulletPower = playerController.currentWave;
}
private void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "Enemy")
{
enemyManager.enemyLife -= bulletPower;
if (enemyManager.enemyLife <= 0)
{
scoreManager.Points += (2 * playerController.currentWave);
enemyManager.enemyLife = playerController.currentWave * 5;
Destroy(col.gameObject);
}
}
}
}
And here is the enemy script:
public class EnemyManager : MonoBehaviour
{
private ScoreManager scoreManager;
private SoundManager soundManager;
private PlayerController playerController;
public int enemyLife;
private void Start()
{
scoreManager = GameObject.Find("Game Manager").GetComponent<ScoreManager>();
soundManager = GameObject.Find("Game Manager").GetComponent<SoundManager>();
playerController = GameObject.Find("Character").GetComponent<PlayerController>();
enemyLife = playerController.currentWave * 5;
}
private void Update()
{
if (playerController.life <= 0)
{
Invoke("Restart", 1);
}
}
private void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "Bullet")
{
soundManager.PlaySound("Enemy Dead");
Destroy(col.gameObject);
}
else if (col.gameObject.tag == "Destroyer")
{
playerController.life--;
}
}
private void Restart()
{
scoreManager.SendToHighScore();
Application.LoadLevel(0);
}
}
The problem is that all of your enemies use the EnemyManager class to manage their health. What your code does is count the amount of hits on all enemies and then destroys the last one that was hit. My suggestion is to add an EnemyStats class to manage stats specific to each enemy (name of the enemy, the amount of damage they can do, weapon graphics, sound effects, the skys the limit). I hate to give you the answer right off the bat (or at least a basic one) since this is a good learning opportunity but here is a basic script that should do what you need and the changes you need to make to your BulletManager script.
EnemyStats.cs (Attach to the enemies game object)
public class EnemyStats : MonoBehaviour
{
public int currentHealth;
public int maxHealth;
public float increasePerWave;
public int bulletPower;
// use a negative value for healing
public void ReduceHealth(int damage)
{
currentHealth -= damage;
}
public bool IsDead()
{
return currentHealth <= 0;
}
public int GetDamage()
{
return bulletPower;
}
/// Restores enemy to their max health for the current wave. Call this after creating an spawning.
public void RestoreHealth(int wave)
{
currentHealth = (int)(maxHealth * increasePerWave * (wave + 1));
}
}
BulletManager update
private void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "Enemy")
{
EnemyStats stats = col.GetComponent<EnemyStats>();
if (stats)
{
stats.ReduceHealth(bulletPower);
if (stats.IsDead())
{
scoreManager.Points += (2 * playerController.currentWave);
Destroy(col.gameObject);
}
}
}
}

Categories