Noticias

¡RECUERDA QUE SI ERES UN NUEVO USUARIO, DEBES PRESENTARTE PARA PODER PUBLICAR MENSAJES! | TENEMOS CANAL OFICIAL DE TELEGRAM: t.me/unity3dspain

ayuda interacicon entre scripts

Iniciado por limelight, Julio 06, 2018, 08:02:59 AM

Tema anterior - Siguiente tema
Julio 06, 2018, 08:02:59 AM Ultima modificación: Julio 06, 2018, 03:00:42 PM por BAMF
Hola que tal tengo un problema en lo que estoy trabajando
 
es shooter en el cual tengo una barra de energia y otra de vida , al momento de disparar se me gasta la de energia (obvio) pero puedo seguir disparando consumiendo desde la barra de vida 
 



   

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;
namespace CompleteProject
{
    public class PlayerHealth : MonoBehaviour
    {
        public int startingHealth = 100;                            // The amount of health the player starts the game with.
        public int currentHealth;                                   // The current health the player has.
        public Slider healthSlider;                                 // Reference to the UI's health bar.
        public Image damageImage;                                   // Reference to an image to flash on the screen on being hurt.
        public AudioClip deathClip;                                 // The audio clip to play when the player dies.
        public float flashSpeed = 5f;                               // The speed the damageImage will fade at.
        public Color flashColour = new Color(1f, 0f, 0f, 0.1f); 
        
        // The colour the damageImage is set to, to flash.
 
        Animator anim;                                              // Reference to the Animator component.
        AudioSource playerAudio;                                    // Reference to the AudioSource component.
        PlayerMovement playerMovement;                              // Reference to the player's movement.
        PlayerShooting playerShooting;                              // Reference to the PlayerShooting script.
        bool isDead;                                                // Whether the player is dead.
        bool damaged;                                               // True when the player gets damaged.
 
        void Awake ()
        {
            // Setting up the references.
            anim = GetComponent <Animator> ();
            playerAudio = GetComponent <AudioSource> ();
            playerMovement = GetComponent <PlayerMovement> ();
            playerShooting = GetComponentInChildren <PlayerShooting> ();
            // Set the initial health of the player.
            currentHealth = startingHealth;
            
        }
 
        void Update ()
        {
            // If the player has just been damaged...
            if(damaged)
            {
                // ... set the colour of the damageImage to the flash colour.
                damageImage.color = flashColour;
            }
            // Otherwise...
            else
            {
                // ... transition the colour back to clear.
                damageImage.color = Color.Lerp (damageImage.color, Color.clear, flashSpeed * Time.deltaTime);
            }
            // Reset the damaged flag.
            damaged = false;
        }
 
        public void TakeDamage (int amount)
        {
            // Set the damaged flag so the screen will flash.
            damaged = true;
            // Reduce the current health by the damage amount.
            currentHealth -= amount;
            // Set the health bar's value to the current health.
            healthSlider.value = currentHealth;
            // Play the hurt sound effect.
            playerAudio.Play ();
            // If the player has lost all it's health and the death flag hasn't been set yet...
            if(currentHealth <= 0 && !isDead)
            {
                // ... it should die.
                Death ();
            }
        }
 
        void Death ()
        {
            // Set the death flag so this function won't be called again.
            isDead = true;
            // Turn off any remaining shooting effects.
            playerShooting.DisableEffects ();
            // Tell the animator that the player is dead.
           // anim.SetTrigger ("Die");
            // Set the audiosource to play the death clip and play it (this will stop the hurt sound from playing).
            playerAudio.clip = deathClip;
            playerAudio.Play ();
            SceneManager.LoadScene(0);
            // Turn off the movement and shooting scripts.
            //playerMovement.enabled = false;
            //playerShooting.enabled = false;
        }
 
       // public void RestartLevel ()
        //{
            // Reload the level that is currently loaded.
          //  SceneManager.LoadScene (0);
        //}
    }
}

   
       
   

[/quote]
 
hasta ahi todo bien, pero en el caso que ya eh usado casi toda la vida si un enemigo me hace daño esta vuelve al valor de 100 osea no hay interaccion entre los scripts 1 me sirve para el daño que recibo de enemigos y el otro para el auto daño para disparar 
 
 
 
si alguien me puede orientar plis
 



   

using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
namespace CompleteProject
{
    public class PlayerShooting : MonoBehaviour
    {
        public int damagePerShot = 20;                  // The damage inflicted by each bullet.
        public float timeBetweenBullets = 0.15f;        // The time between each shot.
        public float range = 100f;                      // The distance the gun can fire.
        PlayerHealth playerHealth;
        public Slider energySlide, healthSlide;
    
       
 
        public float costoDisparo = 10;
        float timer;                                    // A timer to determine when to fire.
        Ray shootRay = new Ray();                       // A ray from the gun end forwards.
        RaycastHit shootHit;                            // A raycast hit to get information about what was hit.
        int shootableMask;                              // A layer mask so the raycast only hits things on the shootable layer.
        ParticleSystem gunParticles;                    // Reference to the particle system.
        LineRenderer gunLine;                           // Reference to the line renderer.
        AudioSource gunAudio;                           // Reference to the audio source.
        Light gunLight;                                 // Reference to the light component.
        public Light faceLight;                                // Duh
        float effectsDisplayTime = 0.2f;                // The proportion of the timeBetweenBullets that the effects will display for.
        void Awake ()
        {
            // Create a layer mask for the Shootable layer.
            shootableMask = LayerMask.GetMask ("Shootable");
            // Set up the references.
            gunParticles = GetComponent<ParticleSystem> ();
            gunLine = GetComponent <LineRenderer> ();
            gunAudio = GetComponent<AudioSource> ();
            gunLight = GetComponent<Light> ();
            //faceLight = GetComponentInChildren<Light> ();
        }
 
        void Update ()
        {
            // Add the time since Update was last called to the timer.
            timer += Time.deltaTime;
        
#if !MOBILE_INPUT
            // If the Fire1 button is being press and it's time to fire...
            if(Input.GetButton ("Fire1") && timer >= timeBetweenBullets && Time.timeScale != 0)
            {
                // ... shoot the gun.
                Shoot ();
            }
#else
             //If there is input on the shoot direction stick and it's time to fire...
            if ((CrossPlatformInputManager.GetAxisRaw("Mouse X") != 0 || CrossPlatformInputManager.GetAxisRaw("Mouse Y") != 0) && timer >= timeBetweenBullets)
            {
                // ... shoot the gun
                Shoot();
            }
#endif
            // If the timer has exceeded the proportion of timeBetweenBullets that the effects should be displa*** for...
            if(timer >= timeBetweenBullets * effectsDisplayTime)
            {
                // ... disable the effects.
                DisableEffects ();
            }
        }
 
        public void DisableEffects ()
        {
            // Disable the line renderer and the light.
            gunLine.enabled = false;
            faceLight.enabled = false;
            gunLight.enabled = false;
        }
 
        void Shoot ()
        {
            // Reset the timer.
            timer = 0f;
            // Play the gun shot audioclip.
            gunAudio.Play ();
            // Enable the lights.
            gunLight.enabled = true;
            faceLight.enabled = true;
            // Stop the particles from playing if they were, then start the particles.
            gunParticles.Stop ();
            gunParticles.Play ();
            // Enable the line renderer and set it's first position to be the end of the gun.
            gunLine.enabled = true;
            gunLine.SetPosition (0, transform.position);
            // Set the shootRay so that it starts at the end of the gun and points forward from the barrel.
            shootRay.origin = transform.position;
            shootRay.direction = transform.forward;
 
            // quitar energia o hp 
            if (energySlide.value > 0)
                energySlide.value -= costoDisparo;
            else if (energySlide.value <= 0 && healthSlide.value > 0)
                healthSlide.value -= costoDisparo;
            else if (healthSlide.value <=0 )
                SceneManager.LoadScene (0);
        
            // Perform the raycast against gameobjects on the shootable layer and if it hits something...
            if (Physics.Raycast (shootRay, out shootHit, range, shootableMask))
            {
                // Try and find an EnemyHealth script on the gameobject hit.
                EnemyHealth enemyHealth = shootHit.collider.GetComponent <EnemyHealth> ();
                // If the EnemyHealth component exist...
                if(enemyHealth != null)
                {
                    // ... the enemy should take damage.
                    enemyHealth.TakeDamage (damagePerShot, shootHit.point);
                }
                // Set the second position of the line renderer to the point the raycast hit.
                gunLine.SetPosition (1, shootHit.point);
            }
            // If the raycast didn't hit anything on the shootable layer...
            else
            {
                // ... set the second position of the line renderer to the fullest extent of the gun's range.
                gunLine.SetPosition (1, shootRay.origin + shootRay.direction * range);
            }
        }
    }
}

   
       
   

[/quote]
 
 

Hola!! El problema es que cuando usas la salud para disparar realmente no cambias la variable currentHealt, solo cambias el valor del slider, la forma "correcta" es hacer referencia al script PlayerHealth y llamar una función cuando uses la salud para disparar, de esta manera desde el script PlayerHealth controlas la vida, el slider y cúando se debe reiniciar el nivel.
 
Si no sabes cómo hacer lo que te he escrito arriba:
 
https://unity3d.com/es/learn/tutorials/topics/scripting/getcomponent?playlist=17117


No tiene nada que ver con el tema, pero tu usuario tiene algo que ver con Naruto?? Me estoy viendo la serie con mi hermano y justo están usando esa palabra

ajsjasjaj sii  y por un tema de rush 
 
volviendo a lo del tema no puede hacerlo :C 

Etiquetas: