C# way of telling how many enemies alive - c#

I have my base game class and an enemy class.
When I instantiate an enemy using the base game I would like a integer to increase
And when one dies I would need it to decrease the integer.
The end result being a new enemy spawns every few seconds so long as that integer is less than my MAX_ENEMIES
any way I'm currently clue less and was hoping someone could direct me with how I should arrange this ( do I have the enemies increase the number when they spawn? )

Here's the basic idea: use a Factory Method. You may want to handle some of the specifics differently.
void Main()
{
var game = new Game();
game.CreateEnemy("Blinky");
Console.WriteLine(game.EnemyCount);
game.CreateEnemy("Clyde");
Console.WriteLine(game.EnemyCount);
game.DestroyEnemy(game.Enemies[0]);
Console.WriteLine(game.EnemyCount);
}
public class Game
{
public List<Enemy> Enemies = new List<Enemy>();
public void CreateEnemy(string name)
{
if (EnemyCount >= MAX_ENEMIES) return;
var enemy = new Enemy { Name = name};
Enemies.Add(enemy);
}
public void DestroyEnemy(Enemy enemy)
{
Enemies.Remove(enemy);
}
public int EnemyCount
{
get { return Enemies.Count(); }
}
}
public class Enemy
{
public string Name { get; set; }
}

Related

Inconsistent function call in C# - Unity 3D

I'm running these functions on an update loop. The first Debug.Log() prints 2 values, the second Debug.Log() prints two different values. How is this possible if one function is calling the other?
private void Blend(Pose pose) {
Debug.Log(pose.name);
// reset previous animation
unBlend(previousPose);
// queue new pose
BlendQ.Enqueue(pose);
}
private void unBlend(Pose pose) {
Debug.Log(pose.name);
// only unblend if new pose is different
//if (pose.name == previousPose.name) return;
if (!running2) {
running2 = true;
StartCoroutine(IRun2(pose.name, pose.curve, pose.blendSpeed));
}
}
public class Pose {
public string name;
public float blendSpeed;
public AnimationCurve curve;
public Pose(string name, AnimationCurve curve, float blendSpeed) {
this.name = name;
this.curve = curve;
this.blendSpeed = blendSpeed;
}
}

Unity code cleaning: writing general shooting script implementing same methods from different bullet classes

I picked up unity and C# a month ago so I'm still a noobie.
So far I managed to build a simple space-based arcade shooter (i have my ship, i have a way to shoot bullets). What I'm trying to achieve is a way to keep the script that takes my keyboard input to shoot separate from the possible bullet types.
The way my bullet types are currently implemented is by having a gameobject for each with its own scripts for a) taking keyboard input and b) instancing a prefab with different properties to shoot. Currently i have 2 shooting modes, and a separate script lets me swap between them with the spacebar by enabling disabling the gameobjects. An example of the scripts I'm using for one bullet type:
Script for instantiating bullet. One method simply shoots every time a button is pressed, the other "charges" an array of bullets, accompanied in the second script by a "growing aura" signifing the power increase. These two methods have the same name across different bullet classes, but are implemented differently.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletA_Basic : MonoBehaviour
{
public GameObject bulletPrefab;
public GameObject aura;
public Transform firingPoint;
public Transform chargingPoint;
public float bulletForce = 20f;
public float altCooldown = 1f;
public float fireRate = 1f;
public float altFirePowerMultiplier = 1f;
private void Update()
{
}
public void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firingPoint);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firingPoint.up * bulletForce, ForceMode2D.Impulse);
}
public void SpecialShoot(int n)
{
StartCoroutine(Special(n));
}
public IEnumerator Special(int n)
{
for (int i = 0; i < n; i++)
{
Shoot();
yield return new WaitForSeconds(0.1f);
}
}
}
Script for taking keyboard input
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting_A : MonoBehaviour //This needs to be copied across all firing types
{
private BulletA_Basic bulletScript; //Change the class to make new projectile types with different firing modes
public Vector3 scaleChange;
private GameObject auraInstance;
private float timePassed = 0f;
private float timePassedMain = 0f;
public float timeToDetonation = 3f;
private void Start()
{
bulletScript = GetComponent<BulletA_Basic>();
}
// Update is called once per frame
void Update()
{
bool isFiring = Input.GetButtonDown("Main Cannon");
bool alternateFire = Input.GetButton("Main Cannon");
timePassedMain += Time.deltaTime;
if (isFiring && timePassedMain > bulletScript.fireRate)
{
bulletScript.Shoot();
timePassedMain = 0;
}
if (alternateFire)
{
timePassed += Time.deltaTime;
if (!auraInstance && timePassed >= bulletScript.altCooldown)
{
auraInstance = Instantiate(bulletScript.aura, bulletScript.chargingPoint);
}
if (alternateFire && auraInstance && timePassed < timeToDetonation)
{
Charge();
//Will need to add shader here
}
else if (timePassed >= timeToDetonation)
{
Destroy(auraInstance);
timePassed = 0;
}
}
else
{
if (auraInstance)
{
Destroy(auraInstance);
int powerAltFire = (int)(bulletScript.altFirePowerMultiplier * (Mathf.Pow(2 , timePassed))); //Equation returns a number of projectiles based on how long charge was held
bulletScript.SpecialShoot(powerAltFire);
}
timePassed = 0;
}
}
void Charge()
{
auraInstance.transform.localScale += scaleChange;
}
}
The key here is the bulletScript field.
Basically i'd like to make the second script general so that i don't have to implement it in a different way and copy-pasting it again and again for each type of bullet I'm going to make, and changing the bulletScript field type each time.
I tried doing it with interfaces but I'm not sure how to implement it in the general script since I need to access each field of the subclasses, which have each their own references (like bulletPrefab, or aura). In general i feel interfaces are not well integrated into unity but that might just be me.
I also tried with delegates, but i had similar problems. I simply changed the type of bulletScript to my delegate type (ShootingDelegate bulletScript), and wrote this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public delegate void ShootDelegate();
public delegate void SpecialShootDelegate(int n);
public class ShootingDelegate : MonoBehaviour
{
public ShootDelegate delShoot;
public SpecialShootDelegate delSpecialShoot;
private int weaponIndex;
public GameObject bulletPrefab;
public GameObject aura;
public Transform firingPoint;
public Transform chargingPoint;
public float bulletForce;
public float altCooldown;
public float fireRate;
public float altFirePowerMultiplier;
// Start is called before the first frame update
void Start()
{
WeaponSwap weapon = GetComponent<WeaponSwap>();
weaponIndex = weapon.weaponIndex;
switch (weaponIndex)
{
case 1:
BulletB_Fan bulletB = GetComponent<BulletB_Fan>();
delShoot = bulletB.Shoot;
delSpecialShoot = bulletB.SpecialShoot;
bulletPrefab = bulletB.bulletPrefab;
aura = bulletB.aura;
firingPoint = bulletB.firingPoint;
chargingPoint = bulletB.chargingPoint;
bulletForce = bulletB.bulletForce;
altCooldown = bulletB.altCooldown;
fireRate = bulletB.fireRate;
altFirePowerMultiplier = bulletB.altFirePowerMultiplier;
break;
case 0:
BulletA_Basic bullet = GetComponent<BulletA_Basic>();
delShoot = bullet.Shoot;
delSpecialShoot = bullet.SpecialShoot;
bulletPrefab = bullet.bulletPrefab;
aura = bullet.aura;
firingPoint = bullet.firingPoint;
chargingPoint = bullet.chargingPoint;
bulletForce = bullet.bulletForce;
altCooldown = bullet.altCooldown;
fireRate = bullet.fireRate;
altFirePowerMultiplier = bullet.altFirePowerMultiplier;
break;
}
}
// Update is called once per frame
void Update()
{
}
}
This is the error it throws:
ArgumentException: Value does not fall within the expected range.
ShootingDelegate.Start () (at Assets/Scripts/ShootingDelegate.cs:54)
which corresponds to this line
delShoot = bullet.Shoot;
I don't really care if a solution employs either interfaces or delegates, those were just things I tried. Any thoughts?
I created a sample just for you.
Here I am creating BulletType parent class for all bullet types. And atting some variable and method for all bullets.
public class BulletType : MonoBehaviour
{
// Protected is less stric than private, more stric than public
// Protected variables only accesible to this class and its child.
protected string name;
protected int bulletDamage;
protected int bulletSpeed;
protected virtual void Start()
{
}
// Virtual means you can override this method in child classes
protected virtual void Damage() { }
public virtual void PlaySound() { }
protected virtual void ShowEffect() { }
}
Now I will add child class and inherit from parent BulletType class. Everything write in comment lines.
// This class inherits from BulletType class.
public class FireBullet : BulletType
{
// If you want to completely ignore parent class variable to by adding new keyword.
new int bulletSpeed = 3;
protected override void Start()
{
// when overriding a method automatically adds this method.
// base means parent class. with base you can access parent methods.
base.Start();
// If you remove base method, parent method won't be called in this class.
// Here I accessed parent class variable and set its value.
// This doesn't effect parent or other child classes. That's the beauty.
name = "Fire Bullet";
}
void StopSound()
{
}
protected override void PlaySound()
{
// Sound played from parent.
base.PlaySound();
// You can add your own variable and methods in parent method.
StopSound();
}
}
// FireBullet inherited from BulletType, and LavaBullet inherited from FireBullet.
// You can do this as much as you want.
public class LavaBullet : FireBullet
{
protected override void PlaySound()
{
// Here base will be FireBullet
base.PlaySound();
}
}
public class IceBullet : BulletType
{
// Add as much as you thing.
}
And for using BulletType script in your player just add this line
public class Player
{
public BulletType currentBulletType;
// You can get child from main class.
FireBullet fireBullet = currentBulletType.GetComponent<FireBullet>();
// Now you can access and use child class methods.
fireBullet.PlaySound();
}
and when you want to change bullet type, just assign new bullettype. Because all bullet type inherit from this class. You can assign every bullet type.
I don't know if it's the answer but,
delShoot = bulletB.Shoot;
delShoot is a reference to a script.
bulletB.Shoot is a function.
I don't think you can make one equal to the other.
If I understand your question, you want to make one script for two type of bullets shoot. You can create a scipts Shoot.cs who is instantiate with a value (1 for the default fire 2 for the second fire) and other scrits defaultFire.cs / secondFire.cs with they own properties.
Like this you'll juste instantiate once your Bullet like this :
public void Start(){
case 1 : Shoot shoot = new Shoot(1)
case 2 : Shoot shoot = new Shoot(2)
}
Hope this help a little..

Using A Dictionary To Hash <String,Class>

I am looking to do a specific task for a small unity game I am doing for class.
In it, I am trying to hash a class that contains variables and a method that is specific to each class created for the dictionary. The variables work fine as they do not need to be static and are not abstract, the method however I am struggling to work with.
Here is my entire script being used.
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
public class EnemyZ : MonoBehaviour
{
// Class used to hash names health assets and then move options
public class EnemySet
{
public string EnemyName { get; set; }
public float EnemyHealth { get; set; }
public void Moves()
{
}
}
//setting EnemySet with names health (assets and move options)
public static void Setup()
{
var cards = new Dictionary<string, EnemySet>()
{
{ "Slime", new EnemySet { EnemyName="Slime", EnemyHealth= 25} },
{ "Flaz", new EnemySet { EnemyName="Flaz", EnemyHealth= 34} },
{ "BandShee", new EnemySet { EnemyName="BandShee", EnemyHealth= 45} },
{"Fan-Natic", new EnemySet{EnemyName = "Fan-Natic", EnemyHealth = 20} }
};
}
void Update()
{
}
}
I am looking to have the Move function be overridden and callable.
How would I set this dictionary of class/method's up and how would I call it once it has been correctly added to the dictionary?
I think you are approaching your class structure and the approach to overwriting your abstract methods incorrectly which is causing the confusion around the dictionary.
I would create an interface for enemies that defines what your enemies need to contain and perform. You can then create an abstract base class the implements common functionality for enemies. Each enemy type should then inherit from your base class.
See below as an example:
// all enemy types must implement the following
public interface IEnemy {
string EnemyName { get; }
float EnemyHealth { get; }
void Move ();
}
// abstract base class for common functionality
public abstract class Enemy : IEnemy {
protected float speed = 0.1f;
public string EnemyName { get; protected set; }
public float EnemyHealth { get; protected set; }
public virtual void Move () {
Debug.Log ($"{EnemyName} moving at {speed}");
}
}
public class Slime : Enemy {
public Slime () {
speed = 0.1f;
EnemyName = "Slimer";
EnemyHealth = 100f;
}
public override void Move () {
Debug.Log ($"{EnemyName} moving at {speed}");
}
}
public class Flaz : Enemy {
public Flaz () {
speed = 0.5f;
EnemyName = "Flaz";
EnemyHealth = 50f;
}
public override void Move () {
Debug.Log ($"{EnemyName} moving at {speed}");
}
}
public class Test : MonoBehaviour {
readonly List<IEnemy> Enemies = new List<IEnemy> ();
void Start () {
var slimer = new Slime ();
Debug.Log ($"{slimer.EnemyName} initialized with health of {slimer.EnemyHealth}");
slimer.Move ();
var flaz = new Flaz ();
Debug.Log ($"{flaz.EnemyName} initialized with health of {flaz.EnemyHealth}");
flaz.Move ();
Enemies.Add (slimer);
Enemies.Add (flaz);
Debug.Log ($"Added {Enemies.Count} enemies");
}
}
I'd say that having a better understanding of classes and interfaces would be good if you wanted to store your enemies in code (the easy way if you're good at object oriented code).
However to answer the question directly I'm going to assume that you're loading enemies from a database or a file or some other non-code format.
In that case I'd go with something like
// Class used to hash names health assets and then move options
public class EnemySet
{
public string EnemyName { get; set; }
public float EnemyHealth { get; set; }
public Action Moves { get; set; }
}
Then when ever you are reading from your datasource to set up the dictionary of enemies I'd have something like
public class EnemyLoader
{
public void MovePawn() => console.WriteLine("I'm a chess piece");
public void MoveZombie() => console.WriteLine("Brains");
public void MoveSlime() => console.WriteLine("Wobbo");
public Action PickMovement(string moveType)
{
switch(moveType)
{
case "pawn": return MovePawn;
case "pawn": return MoveZombie;
default: return MoveSlime;
}
}
public Dictionary<string, EnemySet> LoadEnemies()
{
var dataSource = ReadDataFromSomewhere();
return dataSource.ToDictionary(
k => k.EnemyName,
v => new EnemySet
{
EnemyName = v.EnemyName,
EnemySpeed = v.EnemySpeed,
Move = PickMovement(v.MoveType)
});
}
}

Making an instantiated class array with a method

I have a class "Bullet" which I instantiate using a method CreateBullet(), since there are going to be multiple bullets i decided that I should make bullet an array, though this didn't work out and I've spent an hour on trying to fix it.
What I call in my Initialize method:
Bullet bullet[] = Bullet.CreateBullet[1]();
The Bullet class:
class Bullet
{
public float2 position;
public float angle { get; set; }
public float speed { get; set; }
public static Bullet CreateBullet()
{
Bullet bullet = new Bullet()
{
position = new float2()
};
return bullet;
}
public void Move()
{
}
}
Could you please show me what's wrong with the code? Thank you in advance.
With this, you create an array of 5 bullets:
Bullet[] bullets = new Bullet[5];
And then you need to fill the array by creating a bullet for each array entry:
for (int i = 0; i < bullets.Length; i++)
{
bullets[i] = Bullet.CreateBullet();
}
You can wrap this logic in a function:
public Bullet[] CreateBullets(int amount)
{
Bullet[] bullets = new Bullet[amount];
for (int i = 0; i < bullets.Length; i++)
{
bullets[i] = Bullet.CreateBullet();
}
return bullets;
}
And then you can use a function to initialize the array:
public void Test()
{
Bullet[] bullets = CreateBullets(5);
}
You could do something like this, not quite what you where trying to achieve, but it might inspire you a bit more
Usage
// Create your bullets
var bullets = new List<Bullet>();
// Create a raw/empty bullet with default properties
var newBullet1 = new Bullet();
// Create bullet with some initialized properties
var newBullet2 = new Bullet()
{
Angle = 35,
Position = 0,
Speed = 200
};
bullets.Add(newBullet1);
bullets.Add(newBullet2);
Something extra for fun
// Move all your bullets at once
foreach (var bullet in bullets)
{
bullet.Move();
}

Functions that call functions and/or delegates

Let's say I have an Enemy class with a couple properties and a method AddPoints which will add experience points to an Enemy object. After a certain amount of experience points the Level property of the Enemy object will increase.
Initially I thought 'how can I make the program update the Level property when I don't know when the correct amount of experience points will be reached?. This made me think of events (have to listen for the event to occur, in this case the outcome of the LevelUp() method) so I decided to do something like
private void LevelUp()
{
if (ExperiencePoints > (5 * Level))
{
Level++;
}
}
public void AddPoints(int points)
{
this.ExperiencePoints += points;
LevelUp();
}
This way every time there are points added to the Enemy object the method will check whether or not the Level property needs to be incremented. Having one method call another method made think about containment/delegation (one method is 'nested' inside another). In this way, my AddPoints function sort of acts like a function pointer (at least in my mind).
Does anyone with a knowledge of language design or a good historical knowledge of C++/C# find this a helpful way of thinking about delegates? With the following code is there any way that a delegate can improve the program, or is it too simple?
full Enemy class
class Enemy
{
public int ExperiencePoints { get; set; }
public string Name { get; set; }
private int level;
public int Level
{
get { return level; }
private set { level = value; }
}
private void LevelUp()
{
if (ExperiencePoints > (5 * Level))
{
Level++;
}
}
public void AddPoints(int points)
{
this.ExperiencePoints += points;
LevelUp();
}
public Enemy()
{
ExperiencePoints = 1;
Level = 1;
}
}
testing
delegate void myDelegate(int x);
class Program
{
static void Main(string[] args)
{
Enemy e = new Enemy();
myDelegate del = e.AddPoints;
e.AddPoints(10); //Level =1 at runtime, after this call Level=2
del(20);//now Level=3
Console.WriteLine(e.Level);//output = 3
}
}

Categories

Resources