Score board moves with Character movement in Unity C# - 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).

Related

How to generate ground in unity2d endless runner

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.

Cause player to take damage in Unity 2D

I made two scripts. One that'll keep track of the player's health, health bar and cause the screen to flash when the player is damaged. The other script is meant to be placed on any object I wish to do damage to the player, on contact. My problem is, Nothing seems to be doing any damage to the player.
PlayerHealth.cs:
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour
{
public int currentHealth;
public float flashSpeed = 5;
public Slider healthSlider;
public Color flashColour = new Color(1, 0, 0, 0.1f);
bool isDead;
bool damaged;
private void Awake()
{
currentHealth = 100;
}
private void Update()
{
damaged = false;
}
public void TakeDamage(int amount)
{
damaged = true;
currentHealth -= amount;
healthSlider.value = currentHealth;
}
}
AttackPlayer.cs:
using UnityEngine;
public class AttackPlayer : MonoBehaviour
{
public float timeBetweenAttacks = 0.5f;
public int attackDamage = 10;
GameObject player;
PlayerHealth playerHealth;
float timer;
private void Awake()
{
player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();
}
private void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject == player)
{
Attack();
}
}
private void Update()
{
timer += Time.deltaTime;
if(playerHealth.currentHealth <=0)
{
// TODO: add death script here.
}
}
void Attack()
{
timer = 0f;
if(playerHealth.currentHealth > 0)
{
playerHealth.TakeDamage(attackDamage);
}
}
}
The player has a rigidbody2D. The player and damaging objects have Box Collider 2D's on them.
Make sure that the players Collider has isTrigger enabled.
attackDamage is public -> set in the inspector. Make sure it is not 0.
You could use
[Range(1,100)] public int attackDamage = 10;
to automatically clamp the value in the inspector.
A guess but I'ld say your Collider might not be on the GameObject player but probably on one of its children => the condition col.gameObject == player is not true.
Instead of GameObject references rather compare the PlayerHealth (since there is only one) reference like
private void OnTriggerEnter2D(Collider2D col)
{
// gets PlayerHealth component on this or any parent object
var health = col.GetComponentInParent<PlayerHealth>();
if (health == playerHealth)
{
Attack();
}
}
You have
private void Update()
{
damaged = false;
}
public void TakeDamage(int amount)
{
damaged = true;
currentHealth -= amount;
healthSlider.value = currentHealth;
}
I don't know what else should happen on TakeDamage but the value of damaged is resetted in Update so right after it was set by the Trigger because Physics events like OnTriggerEnter are executed before Update (see execution Order).
Hint: Instead of
player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();
you could also use
playerHealth = FindObjectOfType<PlayerHealth>();
if that component exists only once in your scene.
Or to be more flexible (having multiple Players) all you have to do is change your OnTriggerEnter2D and Attack method to
private void OnTriggerEnter2D(Collider2D col)
{
// gets PlayerHealth component on this or any parent object
var health = col.GetComponentInParent<PlayerHealth>();
if (health != null)
{
Attack(health);
}
}
void Attack(PlayerHealth health)
{
timer = 0f;
if(health.currentHealth > 0)
{
health.TakeDamage(attackDamage);
}
}
So you wouldn't need to get the reference before.

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;
}
}

Unity2D: How to make spawn object gradually go faster after the player collects 10 points?

so I was wondering if there was a way to make a spawned object gradually moves/go faster after the player (you the user) collects 10 points. And faster when the player collects another 10 points and so on and so on?
This is my movement script attach to my objects that get spawned in:
public class Movement : MonoBehaviour
{
public static int movespeed = 20;
public Vector3 userDirection = Vector3.right;
public void Update()
{
transform.Translate(userDirection * movespeed * Time.deltaTime);
}
}
This is my score script attach to my player
public int Score;
public Text ScoreText;
void Start ()
{
Score = 0;
SetScoreText ();
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag ("Pick Up"))
{
other.gameObject.SetActive (false);
Score = Score + 1;
SetScoreText ();
}
}
void SetScoreText ()
{
ScoreText.text = "Score: " + Score.ToString ();
}
And this is my generateEnemy script:
public GameOverManager gameOverManager = null;
[HideInInspector]
public float minBlobSpawnTime = 2;
[HideInInspector]
public float maxBlobSpawnTime = 5;
[HideInInspector]
public bool generateBlobs = true;
[HideInInspector]
public GameObject blobPrefab = null;
[HideInInspector]
public GameObject blobRoot = null;
[HideInInspector]
public float minimumYPosition = -0.425f;
[HideInInspector]
public float maximumYPosition = 0.35f;
[HideInInspector]
public float minDaggerSpawnTime = 2;
[HideInInspector]
public float maxDaggerSpawnTime = 5;
[HideInInspector]
public bool generateDaggers = true;
[HideInInspector]
public GameObject daggerPrefab = null;
[HideInInspector]
public GameObject daggerRoot;
[HideInInspector]
public float minimumXPosition = -11.5f;
[HideInInspector]
public float maximumXPosition = 11.5f;
public Camera camera = null;
// Use this for initialization
void Start ()
{
generateBlobs = ((generateBlobs) && (blobPrefab != null) && (blobRoot != null));
generateDaggers = ((generateDaggers) && (daggerPrefab != null) && (daggerRoot != null));
if (camera == null)
{
Debug.LogError("GenerateEnemy: camera is not set in the inspector. Please set and try again.");
camera = Camera.main;
}
if (gameOverManager == null)
{
Debug.LogError("GenerateEnemy: gameOverManager not set in the inspector. Please set and try again.");
}
if (generateBlobs)
{
StartCoroutine(GenerateRandomEnemy(true, blobPrefab, blobRoot, minBlobSpawnTime, maxBlobSpawnTime));
}
if (generateDaggers)
{
StartCoroutine(GenerateRandomEnemy(false, daggerPrefab, daggerRoot, minDaggerSpawnTime, maxDaggerSpawnTime));
}
}
// Update is called once per frame
void Update ()
{
DestroyOffScreenEnemies();
}
// Spawn an enemy
IEnumerator GenerateRandomEnemy(bool generateOnYAxis, GameObject prefab, GameObject root, float minSpawnTime, float maxSpawnTime)
{
if ((prefab != null) && (gameOverManager != null))
{
if (!gameOverManager.GameIsPaused())
{
GameObject newEnemy = (GameObject) Instantiate(prefab);
newEnemy.transform.SetParent(root.transform, true);
// set this in the prefab instead
// newEnemy.transform.position = new Vector3(newEnemy.transform.parent.position.x, 0.5f, newEnemy.transform.parent.position.z);
// or if you want the y position to be random you need to do something like this
if (generateOnYAxis)
{
newEnemy.transform.position = new Vector3(newEnemy.transform.parent.position.x, Random.Range(minimumYPosition, maximumYPosition), newEnemy.transform.parent.position.z);
}
else
{
newEnemy.transform.position = new Vector3(Random.Range(minimumXPosition, maximumXPosition), newEnemy.transform.parent.position.y, newEnemy.transform.parent.position.z);
}
}
}
yield return new WaitForSeconds(Random.Range(minSpawnTime, maxSpawnTime));
StartCoroutine(GenerateRandomEnemy(generateOnYAxis, prefab, root, minSpawnTime, maxSpawnTime));
}
public void DestroyOffScreenEnemies()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag("enemy");
if ((enemies.Length > 0) && (camera != null))
{
for (int i = (enemies.Length - 1); i >= 0; i--)
{
// just a precaution
if ((enemies[i] != null) && ((camera.WorldToViewportPoint(enemies[i].transform.position).x > 1.03f) ||
(enemies[i].transform.position.y < -6f)))
{
Destroy(enemies[i]);
}
}
}
}
}
(This script has an generateEnemyCustomEditor script that references it, to show in the inspector)
Thank you :)
First of all, remove the static keyword from public static int movespeed = 20; and use GameObject.Find("ObjectMovementIsAttachedTo").GetComponent<Movement>(); to get the script instance if you want to modify movespeed variable from another script.
And faster when the player collects another 10 points and so on and so
on?
The solution is straight on. Use
if (Score % 10 == 0){
//Increement by number (4) movespeed from Movement script
movement.movespeed += 4;
}
to check if the Score is increased by 10 then increment movespeed by any value you want if that condition is true. It makes sense to put that in the OnTriggerEnter2D function after Score is incremented by 1.
Your new score script:
public class score : MonoBehaviour
{
public int Score;
public Text ScoreText;
private int moveSpeed;
void Start()
{
Score = 0;
SetScoreText();
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
other.gameObject.SetActive(false);
Score = Score + 1;
if (Score % 10 == 0)
{
//Increement by number (4) movespeed from Movement script
moveSpeed += 4;
}
SetScoreText();
}
}
public int getMoveSpeed()
{
return moveSpeed;
}
void SetScoreText()
{
ScoreText.text = "Score: " + Score.ToString();
}
}
Since your Movement script will be instantiated, when you instantiate it, you send its reference to the Player script.
public class Movement : MonoBehaviour
{
public int movespeed = 20;
public Vector3 userDirection = Vector3.right;
score mySpeed;
void Start()
{
//Send Movement instance to the score script
GameObject scoreGameObject = GameObject.Find("GameObjectScoreIsAttachedTo");
mySpeed = scoreGameObject.GetComponent<score>();
}
public void Update()
{
transform.Translate(userDirection * mySpeed.getMoveSpeed() * Time.deltaTime);
}
}

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