Hello guys i work on some reflex tapping game in unity and i need script for every 2 or more prefab destroy to add speed on my player and i need that constatly adding speed for 2 prefbas. Can someone help me whit that i do like this:
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Sphere"))
{
count = count + 1;
if(count >= highScore)
{
highScore = count;
PlayerPrefs.SetInt("highscore", highScore);
PlayerPrefs.Save();
}
SetCount();
if(count == 2)
{
rb.AddForce(0, 0, 50 * forwardForce * Time.deltaTime);
}
}
I would recommend making Speed a property of your Player class:
public class Player : MonoBehaviour
{
public float Speed;
}
You would need to make sure to multiply by this property when you move the player (I'm assuming your code is similar to this):
rigidbodyReference.AddForce(0, 0, 50 * Speed * Time.deltaTime);
Then, I would make a static GameManager class that will keep track of the number of prefabs:
public static class GameManager : MonoBehaviour
{
public static PrefabCount;
}
Finally, I would add a speedIncrement variable (exposed to the inspector) as a property of your Player class and modify your OnTriggerEnter method:
public float speedIncrement;
// ...
void OnTriggerEnter(Collider other)
{
// This will reduce unnecessary nesting in your code to make it easier to read
if (!other.gameObject.CompareTag("Sphere"))
return;
// Same thing as GameManager.PrefabCount = GameManager.PrefabCount + 1
GameManager.PrefabCount++;
if (GameManager.PrefabCount >= highScore)
{
highScore = GameManager.PrefabCount;
PlayerPrefs.SetInt("highscore", highScore);
PlayerPrefs.Save();
}
// Use the Modulus operator to determine if the PrefabCount is evenly divisible by 2
if (GameManager.PrefabCount % 2 == 0)
Speed += speedIncrement; // Increase speed by whatever value set in the inspector
}
Related
I am developing a FPS in Unity.
How can I prevent the player from picking up recovery items when the player's HP is 100 (full)?
Currently, players can pick up recovery items even when their HP is full, and I want to limit the conditions for getting them.
The first thing I can think of is to temporarily disable the collision on the recovery item side, when the player's HP is 100.
I want to use collider.enabled = false; in an if statement, how do I write it?
Or am I doing it wrong?
Please surpport me.
HPItem.cs (This is a HPItem)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HPItem : MonoBehaviour
{
public FPSController fPSController;
public int reward = 100;
public AudioClip getSound;
<summary>
</summary>
<param name="collision"></param>
[SerializeField]
public Vector3 speed;
void Start()
{
fPSController = GameObject.Find("Player").GetComponent<FPSController>();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
AudioSource.PlayClipAtPoint(getSound,transform.position);
Destroy(gameObject, getSound.length);
fPSController.AddHP(reward);
}
}
}
FPSController.cs(This is a Player)
int playerHP = 100, maxPlayerHP = 100;
public Slider hpBer;
public void AddHP(int amount)
{
playerHP += amount;
if (playerHP > 100)
{
playerHP = 100;
}
}
It would not be better to check the onTriggerEnter function, once you know that it is the player you check the value of life, if it is 100 you do not collect it
Check the health of the player when the collision happens, only collect if health is not full.
Not a perfect solution (i.e. if player loses health while standing on the health item, they won't pick it up), but you could use OnTriggerStay() for that.
FPSController.cs:
// Add public getter for heath
public int Health => playerHP;
HPItem.cs:
...
void OnTriggerEnter(Collider other)
{
// Add check for health to this if statement.
// && statements are evaluated left to right, so
// no danger of NullReferenceException
if (other.gameObject.tag == "Player" &&
other.GetComponent<FPSController>().Health != 100)
{
AudioSource.PlayClipAtPoint(getSound,transform.position);
Destroy(gameObject, getSound.length);
fPSController.AddHP(reward);
}
}
...
I am very new to c# and I've come across a problem with my enemy spawner. I am making an endless top-down shooter, and after 20 enemies have been spawned and then destroyed, the enemies stop appearing. My score counter continues to increase though, which leads me to believe they're somehow being destroyed.
Here is the enemy spawn controller:
void Update()
{
if (!spawningObject && GameController.EnemyCount < spawnSettings[0].maxObjects)
{
spawningObject = true;
float pick = Random.value * totalWeight;
int chosenIndex = 0;
float cumulativeWeight = enemySpawnables[0].weight;
while(pick > cumulativeWeight && chosenIndex < enemySpawnables.Count - 1)
{
chosenIndex++;
cumulativeWeight += enemySpawnables[chosenIndex].weight;
}
StartCoroutine(SpawnObject(enemySpawnables[chosenIndex].type, Random.Range(spawnSettings[0].minWait / GameController.DifficultyMultiplier, spawnSettings[0].maxWait / GameController.DifficultyMultiplier)));
Spawn();
}
}
private IEnumerator SpawnObject(string type, float time)
{
yield return new WaitForSeconds(time);
randomSpawnPoint = Random.Range(0, enemySpawners.Length);
randomEnemy = Random.Range(0, enemy.Length);
enemyPool.SpawnObject(enemySpawners[randomSpawnPoint].position, transform.rotation);
spawningObject = false;
GameController.EnemyCount++;
}
And here is the enemy controller (attached to enemy prefab):
public void Start()
{
myRB = GetComponent<Rigidbody>();
player = FindObjectOfType<PlayerController>();
}
private void OnEnable()
{
player = FindObjectOfType<PlayerController>();
}
void Update()
{
if (health <= 0)
{
Die();
}
}
void FixedUpdate()
{
transform.LookAt(player.transform.position);
myRB.velocity = (transform.forward * moveSpeed);
//Falling
if(myRB.velocity.y < 0)
{
myRB.velocity += Vector3.up * Physics.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
}
}
public void Die()
{
print("Enemy" + this.gameObject.name + " has died!");
EnemySpawn.instance.enemyPool.ReturnObject(this.gameObject);
player.GetComponent<PlayerController>().points += pointsToGive;
ScoreController.scoreValue += 1;
}
The only thing that should affect enemy health is the bullet. Here is the part of the bullet controller that affects enemy health:
public void OnTriggerEnter(Collider other)
{
if(other.tag == "Enemy")
{
triggeringEnemy = other.gameObject;
triggeringEnemy.GetComponent<EnemyController>().health -= damage;
PlayerController.instance.bulletPool.ReturnObject(gameObject);
}
}
The issue always happens after 20 enemies have been spawned/destroyed and 20 points have been achieved. Before then, enemy movement is normal and everything seems to be working as it should. It could very well be something very simple that I'm missing, but I'd appreciate any help!
When you do engage logic mistake good way to find it is Visual Studio debugging.
Here is good official article about whole process - https://docs.unity3d.com/Manual/ManagedCodeDebugging.html.
I would place breakpoint right at start of Update method to see that EnemyCount increases over time and then you will understand that you forgot to do decrement it.
I want some enemies to spawn in 4 different locations for a survival-type game. The problem is, they all spawn in the same place. Why is this? This is in Unity by the way.
C# script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour {
public int spawnHere = 0;
public int spawnTimer = 0;
public int spawnRate = 1;
public Transform spawner1;
public Transform spawner2;
public Transform spawner3;
public Transform spawner4;
public GameObject melee1;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
spawnTimer = spawnTimer + spawnRate;
spawnHere = Random.Range (1, 5);
if(spawnTimer >= 120) {
if(spawnHere == 1) {
Instantiate (melee1, spawner1);
}
if(spawnHere == 2) {
Instantiate (melee1, spawner2);
}
if(spawnHere == 3) {
Instantiate (melee1, spawner3);
}
if(spawnHere == 4) {
Instantiate (melee1, spawner3);
}
spawnTimer = 0;
}
}
}
Have you connected the spawners correctly in the UI?
Watch this: Unity - Survival Shooter - Spawning Enemies
This worked pretty good for my project.
You should also use Time.deltaTime for timing the spawns. Not every system outputs the same amount of frames / second.
Unity - docs - Time.deltaTime
BTW:
Random.rand(min, max)
Unity - docs - Random.Rand
includes max as a possible value.
I want to make my spawned objects (enemy prefabs) movement speed up every 10 points my player collects.
This is my movement script, attached to my enemy prefab (so that it can be spawned in my game and move):
public static int movespeed = 20;
public Vector3 userDirection = Vector3.right;
public void Update()
{
transform.Translate(userDirection * movespeed * Time.deltaTime);
}
}
And this is my score script attached to my player:
public Text ScoreText;
public AudioClip Coinsound;
public Text Highscoretext;
public GameObject enemy;
Movement movement;
private int Score;
public int highScore = 0;
void Start ()
{
Score = 0;
SetScoreText ();
if (PlayerPrefs.HasKey ("Highscore"))
{
highScore = PlayerPrefs.GetInt("Highscore");
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag ("Pick Up")) {
other.gameObject.SetActive (false);
Score = Score + 1;
SetScoreText ();
AudioSource.PlayClipAtPoint (Coinsound, transform.position);
}
}
As mentioned before I want to make my spawned enemy prefabs to move faster when my player collects every ten points. Thank you :)
You use the % symbol to do that. After adding 1 to Score, Check if there is a reminder when Score is divided by 10. If there is no remainder, increment. Don't increment of there is a remainder.
if (Score % 10 == 0){
//Increment movespeed variable from Movement script
Movement.movespeed += 4;
}
Put the code above in your OnTriggerEnter2D function.
For some reason, this looks very similar to another question but the OP failed to get that answer working.
I'm making a 'run' game in Unity and I'm making a prototype with a ball, that has other balls following him. If the followers hit an object they get destroyed after some time. To make it so you don't run out of enemies I made a trigger that spawns new enemies. In the code this is the function Addzombies.
How do I make them spawn not on the same point, if i run it now they
start on eachother and bounce around as an explosion.
How do i make some start in the air, i tried it but they don't
spawn.
My code:
using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour {
public float InputForce;
public GUIText guiText;
public float rotationHorizontal;
public AudioClip ACeffect2;
public GameObject zombiePrefab;
void FixedUpdate() {
rigidbody.AddForce( Camera.main.transform.right * Input.GetAxis("Horizontal") * InputForce);
rigidbody.AddForce( Camera.main.transform.forward * Input.GetAxis("Vertical") * InputForce);
transform.position += Vector3.forward *InputForce * Time.deltaTime;
rotationHorizontal = Input.GetAxis("Horizontal") * InputForce;
rotationHorizontal *= Time.deltaTime;
rigidbody.AddRelativeTorque (Vector3.back * rotationHorizontal);
}
void OnCollisionEnter(Collision col){
if (col.gameObject.name == "Zombie") {
Debug.Log ("Player geraakt, nu ben je eigenlijk dood");
}
if (col.gameObject.name == "Obstakel1") {
Debug.Log ("Obstakel1 geraakt");
audio.PlayOneShot(ACeffect2);
InputForce = 0;
}
if (col.gameObject.name == "Obstakel2") {
Debug.Log ("Obstakel2 geraakt");
}
}
void AddZombies(int aantal){
for (int i = 0; i < aantal; i++){
GameObject go = GameObject.Instantiate(zombiePrefab, transform.position - new Vector3(0, 0, 7 + i),Quaternion.identity) as GameObject;
Zombie zb = go.GetComponent<Zombie>();
zb.target = gameObject.transform;
}
}
void OnTriggerEnter(Collider col) {
Debug.Log ("Enter" +col.name);
if (col.tag == "AddZombies"){
AddZombies(4);
}
}
void OnTriggerExit(Collider col) {
Debug.Log ("Leaving with" +col.name);
}
}
I will advice on how things could be done, but you will have to make changes to make it suit your requirement
public Transform zombiePrefab; // From the editor drag and drop your prefab
void addZombies()
{
// as you need them to be not on the same point
int randomX = Random.Range(-10.0F, 10.0F);
for (int i = 0; i < aantal; i++){
// make a transform
var zombieTransform = Instantiate(zombiePrefab) as Transform;
zombieTransform.position = new Vector3(randomX, 0, 7 + i);
transform.GetComponent<Rigidbody>().enabled = false;
// make it enable when you need and add force to make them fall
}
}
I would suggest passing the number of zombies to pass, and an integer representing the range of space that they can spawn in. Then just use UnityEngine.Random with said integer for each zombie to produce several different co-ordinates for spawning the zombies.
As for getting them to spawn in the air, just increase the y co-ordinate when you instantiate the zombie.