Unity C# Attempting to make a lava collider, death script - c#

So far my script is below. I am attempting to create another Collider part to the script, I am attempting to make it so when you collide with Lava, which has a Tag named lava, the player will die. However, I can't get it to call for the die function and I also can't use OnTriggerEnter(collider,other) as it gives me an error.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
// Player Movement Start
{
public float speed;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
}
//End of Player Movement Script
//Pickups Script
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
other.gameObject.SetActive(false);
}
}
//End of Pickups Script
//Health and Death Script
public float health;
public GameObject Ragdoll;
public void TakeDamage(float dmg){
health -= dmg;
if (health <= 0) {
Die();
}
}
public void Die() {
Application.LoadLevel(Application.loadedLevel);
}
}
//End of Health and Death script

According to the answer here,
The access level for class members and struct members, including
nested classes and structs, is private by default.
With this logic, and knowing that OnTriggerEnter(...) must be called from outside of your MonoBehaviour, you should probably explicitly make it public
Also, you say you are trying to run your Die(...) method from the OnTriggerEnter(...) function, but i dont see that in your code, it should look as follows:
public void OnTriggerEnter(Collider other)
{
switch (other.tag)
{
case "Pick Up": other.gameObject.SetActive(false);
break;
case "Lava": Die();
break;
}
}

Related

Power-Ups increasing projectile stats

I am trying to increase the damage of the players fireball when a power up is picked up. I am getting an object reference error, I'm pretty sure this is due to the code being linked tot he player for the collision and the fireballs have their own script detailing their speed, damage etc.
Essentially I need a way to reference my fireball prefab (Called Bullet) so the code can access the 'damage' stat and increase it for a period of time.
The code for the power-up is:-
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Pickup(other);
}
}
void Pickup(Collider2D player)
{
Instantiate(pickupEffect, transform.position, transform.rotation);
Fire stats = GetComponent<Fire>();
stats.damage *= 2;
Destroy(gameObject);
}
}
**The code for the fireball prefabs (known as Fire) is:-**
public class Fire : MonoBehaviour
{
public Animator animator;
public float speed = 20f;
public int damage = 30;
public Rigidbody2D rb;
public GameObject FireEmbers;
public float liveTime = 1f;
// Start is called before the first frame update
void Start()
{
rb.velocity = transform.right * speed;
}
void OnTriggerEnter2D(Collider2D hitInfo)
{
Enemy enemy = hitInfo.GetComponent<Enemy>();
if (enemy != null)
{
enemy.TakeDamage(damage);
}
Destroy(gameObject);
Instantiate(FireEmbers, transform.position, Quaternion.identity);
}
void Update()
{
liveTime -= Time.deltaTime;
if (liveTime <= 0)
{
Destroy(this.gameObject);
Instantiate(FireEmbers, transform.position, Quaternion.identity);
}
}
}
I actually resolved this by using scriptable objects instead of hard coding things into prefabs.

error CS7036: There is no argument given that corresponds to the required formal parameter 'player' can't figure out the issue with the code?

I'm still new to coding and this issue has me stuck.
I was following a tutorial video on how to make a power up script but for some reason, it doesn't function.
I've been looking around for a solution but none of them seem to work. Any help would be appreciated!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PowerUpPickupEffect : MonoBehaviour
{
public GameObject pickupEffect;
public float multiplier = 2.0f;
void OnTriggerEnter2D (Collider2D other)
{
if (other.CompareTag ("Player"))
{
Pickup ();
}
}
void Pickup (Collider player)
{
Instantiate (pickupEffect, transform.position, transform.rotation);
player.transform.localScale *= multiplier;
Destroy (gameObject);
}
}
Your method PickUp expects a Collider as parameter.
However: Note that Collider != Collider2D They are from completely two separated and independent physics engines Physics and Physics2D!
For 2D it should rather be
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
// pass in the expected argument
Pickup(other);
}
}
void Pickup(Collider2D player)
{
Instantiate(pickupEffect, transform.position, transform.rotation);
player.transform.localScale *= multiplier;
Destroy(gameObject);
}
or for 3D
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
// pass in the expected argument
Pickup(other);
}
}
void Pickup(Collider player)
{
Instantiate(pickupEffect, transform.position, transform.rotation);
player.transform.localScale *= multiplier;
Destroy(gameObject);
}

unity5 enemyDamage prob

im having a problem from my enemyDamage script in unity5 when i play it and stick to the enemy i died instantly even the enemy damage is 10 and my health was 100
well this is my first time to make this things on unity hope you helps me :(
heres my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemydmg : MonoBehaviour {
public float damage;
public float damagerate;
public float pushbackforce;
float nextdamage;
bool playerInRange = false;
GameObject theplayer;
playerHealth theplayerhealth;
// Use this for initialization
void Start () {
nextdamage = Time.time;
theplayer = GameObject.FindGameObjectWithTag ("Player");
theplayerhealth = theplayer.GetComponent<playerHealth> ();
}
// Update is called once per frame
void Update () {
if (playerInRange)
Attack ();
}
void OnTriggerEnter (Collider other)
{
if (other.tag == "Player")
{
playerInRange = true;
}
}
void OnTriggerExit (Collider other)
{
if (other.tag == "Player")
{
playerInRange = false;
}
}
void Attack()
{
if (nextdamage <= Time.time)
{
theplayerhealth.addDamage(damage);
nextdamage = Time.time + damagerate;
pushback (theplayer.transform);
}
}
void pushback(Transform pushObject)
{
Vector3 pushDirection = new Vector3 (0, (pushObject.position.y - transform.position.y), 0).normalized;
pushDirection *= pushbackforce;
Rigidbody pushedRB = pushObject.GetComponent<Rigidbody> ();
pushedRB.velocity = Vector3.zero;
pushedRB.AddForce (pushDirection, ForceMode.Impulse);
}
}
and this was my playerhealth
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerHealth : MonoBehaviour {
public float fullhealth;
float currentHealth;
// Use this for initialization
void Start () {
currentHealth = fullhealth;
}
// Update is called once per frame
void Update () {
}
public void addDamage(float damage)
{
currentHealth -= damage;
if (currentHealth <= 0) {
makeDead ();
}
}
public void makeDead()
{
Destroy (gameObject);
}
}
theplayerhealth = theplayer.GetComponent<playerHealth> ();
I think this line of code fails you because the player is a GameObject. theplayerhealth is or should already be initialized in your other script. I think you could approach polymorphism in a better way.
public class enemydmg : playerHealth{
}
This will allow you to directly inherit everything you need from the playerHealth script without having to grab extra components. You can also use this technique for may other scripts in the future.
Another approach that you could use is calling your class directly:
playerHealth.addDamage(damage);
From now on when you name your scripts use capitalization. PlayerHealth, EnemyDamage, etc... That's just a pro-tip to make your code look a bit cleaner when you're doing things like this. (Optional)

Programming a 2d enemy in c#

I have been working on enemies in my game, but feel the code is clunky as is and also does not seem to work. I put code into my player script and enemy script. the player script is as follows:
EDIT: sorry for not being clear enough, here are the lines of code that do not work and what I want them to do:
void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
Destroy (this.gameObject);
}
}
What i want in this code is for when the player encounters an enemy or object with the "Enemy" tag, touching that object will destroy or kill the player object.
void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag == "Killable")
{
Debug.Log ("entering killzone!");
Destroy (other.gameObject);
Instantiate (DeadStar, transform.position, Quaternion.identity);
this.gameObject.SetActive (false);
}
}
}
This code was loosely copied from a previous game, this has bits of it's killzone and was made to destroy the player object when it touches any object that contains this script. (the player is tagged "Killable")
hope this edit helps, im a little tired and forgot to specify things, sorry about that.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float JumpSpeed;
public float Scale;
public string JumpKey;
public string LeftKey;
public string RightKey;
public float speed;
public GameObject Player;
public Rigidbody2D rb;
void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
Destroy (this.gameObject);
}
}
void Start()
{
GetComponent<Rigidbody2D>().freezeRotation = true; /*GetComponent<Rigidbody>().angularVelocity = Vector3.zero;*/
rb = GetComponent (typeof(Rigidbody2D)) as Rigidbody2D;
}
void FixedUpdate ()
{
Vector3 hold = rb.velocity;
hold.x = 0;
if (Input.GetKey (LeftKey))
{
hold.x -= speed;
}
if (Input.GetKey (RightKey))
{
hold.x += speed;
}
if (Input.GetKeyDown (KeyCode.Space))
{
hold.y = JumpSpeed;
}
rb.velocity = hold;
}
}
The enemy script is as follows:
using UnityEngine;
using System.Collections;
public class EnemyKillzone : MonoBehaviour {
public GameObject DeadStar;
public GameObject Player;
void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag == "Killable")
{
Debug.Log ("entering killzone!");
Destroy (other.gameObject);
Instantiate (DeadStar, transform.position, Quaternion.identity);
this.gameObject.SetActive (false);
}
}
}

Bullet not going towards target

Not sure why, I've done this sort of this a bunch of times, but this is giving me some issues. Making a project for Game AI, I have a whole bunch of stuff already done, now just making some turrets that if the player is in a certain range it will fire, which I have already. The turret fires the bullet and then for some reason they just start destroying themselves and they don't go towards my player. Wondering if anyone on here can help, thanks in advance!
Some details you may need to know:
I have a Base, a Gun nose and a Gun for my turret. My Gun has a GunLook.cs script that makes it look at the player (so when they shoot it should go towards them), I'm not sure if that has anything to do with why I'm having these issues, but I'll post that code as well just incase
How my Hierchy for my turret is
Turret_AI (Base)
Gun (child of Turret_AI)
bulletSpawn (child of Gun)
Gun_Nose (child of turret_AI)
bulletSpawn is an empty GameObject I created in hopes to solve my problem. I set it just off the Gun so that it wouldn't just collide with gun and destroy itself (what I thought it might be doing, but not correct).
That should be all the info needed, if anyone needs more I will be checking this every 2 seconds so let me know and I will get back to you with quick response.
TurretScript.cs
(I did set the GameObject to Player in Unity, before anyone asks)
using UnityEngine;
using System.Collections;
public class TurretScript : MonoBehaviour {
[SerializeField]
public GameObject Bullet;
public float distance = 3.0f;
public float secondsBetweenShots = 0.75f;
public GameObject followThis;
private Transform target;
private float timeStamp = 0.0f;
void Start () {
target = followThis.transform;
}
void Fire() {
Instantiate(Bullet, transform.position , transform.rotation);
Debug.Log ("FIRE");
}
void Update () {
if (Time.time >= timeStamp && (target.position - target.position).magnitude < distance) {
Fire();
timeStamp = Time.time + secondsBetweenShots;
}
}
}
GunLook.cs
// C#
using System;
using UnityEngine;
public class GunLook : MonoBehaviour
{
public Transform target;
void Update()
{
if(target != null)
{
transform.LookAt(target);
}
}
}
BulletBehavior.cs
using UnityEngine;
using System.Collections;
public class BulletBehavior : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (rigidbody.velocity.magnitude <= 0.5)
Destroy (gameObject);
}
void OnCollisionEnter(Collision collision)
{
if (collision.collider)
{
if(collision.gameObject.tag == "Enemy" || collision.gameObject.tag == "EnemyProjectile")
{
Physics.IgnoreCollision(rigidbody.collider,collision.collider);
//Debug.Log ("Enemy");
}
if(collision.gameObject.tag == "SolidObject")
{
Destroy(gameObject);
}
if(collision.gameObject.tag == "Player")
{
Destroy(gameObject);
}
}
}
}
You're never moving your bullet.
public class BulletBehavior : MonoBehaviour
{
private const float DefaultSpeed = 1.0f;
private float startTime;
public Vector3 destination;
public Vector3 origin;
public float? speed;
public void Start()
{
speed = speed ?? DefaultSpeed;
startTime = Time.time;
}
public void Update()
{
float fracJourney = (Time.time - startTime) * speed.GetValueOrDefault();
this.transform.position = Vector3.Lerp (origin, destination, fracJourney);
}
}
Then call it like so:
void Fire()
{
GameObject bullet = (GameObject)Instantiate(Bullet, transform.position , transform.rotation);
BulletBehavior behavior = bullet.GetComponent<BulletBehavior>();
behavior.origin = this.transform.position;
behavior.destination = target.transform.position;
Debug.Log ("FIRE");
}
Note: If you're trying to mix this approach with trying to use physics to move the bullet you may end up with strange results.

Categories

Resources