Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Temas - ramunda

#1
General (Antiguo) / Moverse al enemigo
Diciembre 20, 2018, 06:15:33 PM
Buenas tardes a todos/todas, es una tonteria pero me he liado.
 
estoy haciendo que dos pequeños ejercitos se peguen de leches unos con otros y para eso he creado (creo) la manera que detecte al enemigo mas cercano.
 
Hasta aqui va ok, me dice la distancia y detecta al tag requerido, pero me he atascado a la hora de decirle que si la distancia es +o- la esti***da el agresor vaya hacia ese objetivo.
 
Moverse se mueve pero no se para al llegar al ojectivo! el sigue palante .
 
 
 

public class Enemy : MonoBehaviour
{
    public float curDist = 20;
    GameObject[] enemigos;
    GameObject enemigo;
    public GameObject player;
    public float MoveSpeed = 3f;
    void Update()
    {
       
            enemigos = GameObject.FindGameObjectsWithTag("enemy1");
            curDist = 1;
            foreach (GameObject item in enemigos)
            {
                float dist = Vector3.Distance(player.transform.position, item.transform.position);
                if (dist >= curDist) ;
                {
                    curDist = dist;
                    enemigo = item;
                    print(dist);
                    player.transform.position += transform.forward * MoveSpeed * Time.deltaTime;
                }
            }
           
    }
}

 
seguro que es un tonteria pero me he bloqueado!, agradezco una mano , gracias de antemano y Feliz Navidad!
 
 
#2
General (Antiguo) / Problema on trasform enemigo(Resuelto)
Septiembre 21, 2018, 02:57:03 PM
Buenas tardes, llevo dos dias rompiendome la cabeza de este problema, veran;
 
Tengo un enemigo que me persigue a distgancia x me ataca a distancia x...eso va perfecto, a la hora de activar un simple canvas que es una imagen de sangre en la pantalla solo lo activa el primer enemigo los demas pasan de activar nada.
 
Creo que el problema puede ser en el transform(ahora lo vereis en el script), lo mismo me pasa al activar audios etc solo uno lo hace los demas aunque aga prefab no funciona.
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
 
public class enemigoataca2 : MonoBehaviour
{
    public Transform player;
    public float velocidadenemigo;  
    public float distance;
    public AudioSource pega;
    public AudioSource camina;
    public AudioSource espadahit;
   
 
    void Start()
    {
        player = GameObject.FindGameObjectWithTag("player").transform;
        pega.enabled = false;
        camina.enabled = false;
        espadahit.enabled = false;
       
 
    }
    void Update()
    {
        distance = Vector3.Distance(transform.position, player.position);
        if (distance <= 30)
        {
            camina.enabled = true;
            pega.enabled = false;
            GetComponent<Animation>().CrossFade("Walk");
            GetComponent<walkmesh2>().enabled = false;
            GetComponent<UnityEngine.AI.NavMeshAgent>().SetDestination(player.transform.position);
           
        }
        if (distance <= 3)///AQUI DEBERIA ACTIVAR EL CANVAS SANGRE/AUDIO LO QUE SEA
        {
           GetComponent<Animation>().CrossFade("2H_skeleton_specal_attack_A");
            ManagerScript.manager.Vida -= 5f * Time.deltaTime;
            ManagerScript.manager.activasangre = true;
            pega.enabled = true;
            // player.GetComponent<Animation>().Play("Cover_sword_hit");
            espadahit.enabled = true;
        }
        else
        {
           
            espadahit.enabled = false;
            // player.GetComponent<Animation>().CrossFade("Run");
            ManagerScript.manager.activasangre = false;
        }
       
     
        if (distance >= 25)
        {
            camina.enabled = false;
            GetComponent<walkmesh2>().enabled = true;
        }
    }
}

 
Donde le digo que si la distancia es-= 3 es donde deberia activarlo.
 
y creo que el problema viene de : player = GameObject.FindGameObjectWithTag("player").transform;
 
que solo calcula la distancia de el player en un solo enemigo.
 
 
 
Agradeceria una idea gracias!!!
 
 
 
 
#3
General (Antiguo) / Serializar objetos( Resuelto)
Septiembre 09, 2018, 11:00:23 PM
Buenas a todos, sere lo mas claro posible, empece un proyecto al estilo witcher3 , un mago con echizos etc.
 
Consegui que se guardara la posición de el personaje y los valores de vida y  mana, pero ahora me encuentro que ese echizo que aprendio el personaje ayer hoy no esta aprendido porque no se guarda(canvas imagenes etc).
 
La pregunta es, alguien me da una idea de como implementar estos objetos y que se guarden como lo del mana y la vida?, mire tutos y cofeccione esto por mi cuenta satisfactoriamente.
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class GameControl : MonoBehaviour
{
    public static GameControl control;
    public float vida;
    public float mana;
   
    //public GameObject ballfire;
    void Awake()
    {
        if (control == null)
        {
            DontDestroyOnLoad(gameObject);
            control = this;
        }
        else if (control != this)
        {
            Destroy(gameObject);
        }
    }
    public void Save()
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");
        PlayerData data = new PlayerData();
       
        data.vida = vida;
        data.mana = mana;
       
        bf.Serialize(file, data);
        file.Close();
    }
    public void Load()
    {
        if (File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
            PlayerData data = (PlayerData)bf.Deserialize(file);
            file.Close();
            vida = data.vida;
            mana = data.mana;
           
           
        }
 
    }
}
[System.Serializable]
public class PlayerData
{
    public float vida;
    public float mana;
    //public GameObject ballfire;
   
 
}
 

 
con esto lo llamo desde cualquier parte y me guarda los valores vida y mana, pero como meto aqui los objetos, por ejemplo el mago encuentra un libro el cual le otorga un nuevo echizo que aparece en su barra de echizos(imagenes canvas que se ativan etc)??
 
O debo de meter el script aqui dentro? usando updates y voids starts?
 
 
 
gracias de antemano
#4
General (Antiguo) / quitar vida a scipt enemigo
Agosto 04, 2018, 05:10:19 PM
Buenas tardes a todos/todas, cada vez que unity cambia de versión algo cambia en el codigo....
 
Aver estoy haciendo algo sencillo,tengo unos monigotes enemigos llamados "enemigo", los cuales tienes un script llamado Health.
 
Bien , la idea es que quiero quitarles vida, para ello los busco en este afragmento de codigo:
 

else if (ataca)
        {
            GetComponent<Animation>().CrossFade("vc_uppercut_jab");
            audiopega.enabled = true;
            if (attackDist <=2f)
            {
              GameObject.Find("enemigo").GetComponent<Health>().vida -= 80f * Time.deltaTime;
             
            }

 
busco el objeto, (enemigo). le cojo el script(health). y realizo lo que hace en este caso le quita vida cada segundo.
 
Pero nada...no me encuentra el enemigo.....me tira este error en la linea donde esta el find...
 
NullReferenceException: Object reference not set to an instance of an object
 
alguna idea por favor?
 
Gracias de antemano
 
 
 
 
 
 
 
 
 
 
 
 
#5
General (Antiguo) / Capturar String de Inputfield(Resuelto)
Septiembre 24, 2017, 03:48:45 PM
Buenas tardes, agradecería por favor una mano en un pequeño problema que tengo.
 
Estoy terminando un proyecto y ahora me encuentro con esto...
 
La cosa es sencilla , tengo un simple inputfield el cual me deja insertar lo que quiera..
 
Lo que intento es capturar esa String en un playerpreff para luego usar ese texto en otra pantalla.
 
Prove esto;
 

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
 
public class Loguin : MonoBehaviour
{
public InputField insertarcodigo;
string codigo;
 
void Start()
{
   PlayerPrefs.SetString("Codigo",codigo);
   PlayerPrefs.Save();
}
void Update()
{
   if (Input.GetKeyDown ("space"))
   {
      codigo = insertarcodigo.text;
      PlayerPrefs.GetString ("Codigo");
      //Debug.Log ("El codigo es:" + codigo);
      Debug.Log ("El codigo es:" + PlayerPrefs.GetString ("Codigo"));
   }
}
}

 
pero nada, cuando llamo al pref GetString pensaba que me cojeria la string de codigo pero no.
 
si le llamo al debug directamente a la string(codigo), si me lo da pero lo que quiero es que me la guarde y no lo hace.
 
Agradecería una ayuda por favor, asi puedo terminar este proyecto. muchas gracias de antemano.
 
 
 
 
 
 
 
 
#6
Buenas noches , tengo un dilema con una bola de un juego tipo "arkanoid" que estoy montando.
 
Todo va bien excepto cuando la bola vuelve a la plataforma , allí deberían resetearse las fisicas que le aplico en el start.
 
Para ello uso la función de el Rigidbody2D y lo pongo en kinematico, creía que con esto bastaria....pero no , cada vez que renace la bola va mas rápida, evidentemente esta duplicando la fuerza asignada en el start....pero no se porque!
 
Espero que puedan ayudar.
 
Alla va el script:
 
 
 

using UnityEngine;
using System.Collections;
public class BallScript : MonoBehaviour {
private bool ballIsActive;
private Vector3 ballPosition;
private Vector2 ballInitialForce;
public GameObject playerObject;
public AudioClip hitSound;
AudioSource audio;
private Rigidbody2D rb;
void Start ()
{
   rb = GetComponent<Rigidbody2D>();
   ballIsActive = false;
   ballInitialForce = new Vector2 (50.0f,300.0f);
   ballPosition = transform.position;
   audio=GetComponent<AudioSource>();
}
 
void Update ()
{
   
   if (Input.GetButtonDown ("Jump") == true)
   {
      
      if (!ballIsActive)
      {
         ///reseteamos la fuerza?
         rb.isKinematic = false;
         rb.AddForce (ballInitialForce);
         ballIsActive = !ballIsActive;
      }
   }
   if (!ballIsActive && playerObject != null)
   {
           ballPosition.x = playerObject.transform.position.x;
      transform.position = ballPosition;
   }
}
   
void OnCollisionEnter2D(Collision2D collision)
{
   if (ballIsActive)
   {
      audio.PlayOneShot (hitSound);
}
   if (collision.gameObject.tag == "mata")
   {
      if (ballIsActive)
      {   
         
         Debug.Log ("muere");
         ballIsActive = !ballIsActive;
         ballPosition.x = playerObject.transform.position.x;
         ballPosition.y = -4.5f;
         transform.position = ballPosition;
         rb.isKinematic = true;
         playerObject.SendMessage ("TakeLife");
      }
   }
}
}
   
 

 
 
#7
Buenas tardes,
 
Tengo un pequeño dilema y no se porque no funciona, seguramente es una tontería pero llevo 2 horas comiéndome la cabeza y no logro encontrar el porque!
 
Tengo un script desde donde controlo las cosas."GameControl";
 

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameControl : MonoBehaviour
{
public static GameControl instance;         //referencia del gamee control script que podemos acceder instantaneamente.
public Text scoreText;                  
private int puntos = ;                  
public bool gameOver = false;            
public float scrollSpeed = -1.5f;
public GameObject gameoverr;
public int vidas =;
public Text vidasText;   
 
void Awake()
{
   //si no tenemos el  control...
   if (instance == null)
      //...lo llamamos...
      instance = this;
   //...de lo contrario...
   else if(instance != this)
   //...destruye este porque esta duplicado.
      Destroy (gameObject);
}
void Start()
{
   gameoverr.SetActive (false);
   PlayerPrefs.SetInt ("MyScore",);
   //PlayerPrefs.SetInt ("vidas",0);
   vidasText.text = "Lives: " + vidas.ToString();
}
void Update()
{
   if (vidas <= )
   BirdDied ();
}
public void BirdScored()
{
//      //si el player no puede hacer mas puntos y acabo la partida.
   if (gameOver)   
   return;
   //si el juego no ha terminado, aumentamos el score...
   puntos += 1;
   //...i lo mostramos en el score.
   PlayerPrefs.SetInt ("MyScore", puntos);
   scoreText.text = "Score: " + puntos.ToString();
   vidasText.text = "Lives: " + vidas.ToString();
}
public void BirdDied()
{
   //Activa el gameover.
   gameOver = true;
   gameoverr.SetActive (true);
   PlayerPrefs.GetInt ("MyScore");
}
public void quitavida()
{
   vidas -= 1;
}
}

 
y tengo este otro que registra  un raycast que si no colisiona con el gametag granjero hace una animación y después destruye el GO.
 
Hasta aqui bien la cosa viene cuando le quiero decir que si no has clickado encima de el GO,con el tag " granjero", que se active el sistema de quitar una vida pasados 6 segundos, para eso llamo  a la coorutina quitavida, la cual espera 6 segundos e instancia el void quitavid que se encuentra en el script anterior.Pero no hace tal cosa!
 
este es el script ;
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class tocagranjero : MonoBehaviour
{
private Animator anim;   
private Rigidbody2D rb2d;   
private GameObject gamecontrol;
public AudioSource audio2;
AudioSource audio;
 
void Start()
{
   anim = GetComponent<Animator> ();
   rb2d = GetComponent<Rigidbody2D>();
   audio = GetComponent<AudioSource> ();
   gamecontrol = GameObject.Find ("GameControl");
 
}
IEnumerator quitavida()
{
   yield return new WaitForSeconds(6);
   GameControl.instance.quitavida ();
   Debug.Log ("te quito una vida");
}
void Update ()
{
   if (Input.GetMouseButtonDown ())
   {
      Vector3 mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
      Vector2 mousePos2D = new Vector2 (mousePos.x, mousePos.y);
      RaycastHit2D hit = Physics2D.Raycast (mousePos2D, Vector2.zero);
      if (hit.collider != null)
      {
         Debug.Log (hit.collider.gameObject.name);
         if (hit.collider.tag == "granjero")
         {
         anim.SetTrigger ("tocado");
         GameControl.instance.BirdScored ();
         Destroy (hit.transform.gameObject, 2);
         audio2.Play ();
         }
      }
   }
   else
   {  
   StartCoroutine ("quitavida");
   }
}
}

 
Espero que sea lo que digo una tontería....y que alguno de ustedes pueda decírmela, muchas gracias de antemano.
 
 
 
 
 
 
#8
Buenas tardes, tengo que terminar un dichoso proyecto de la uni i me veo que no lo terminare a menos que me puedan echar un cable.
 
Veamos necesito mandar el valor de este int(ver script mas abajo), a un archivo php ( http://adisfrutar/prova.php?  )
 
pero he foreado mucho i no saco nada en claro.
 
alguna idea por favor?
 
 
 
aqui el script de el score:
 
 
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class score : MonoBehaviour
{
AudioSource audio;
int puntos = ;
public Text puntuacion;
public Animation anim;
void Start()
{
   audio = GetComponent<AudioSource>();
}
void OnTriggerEnter(Collider c)
{
   if (c.gameObject.tag == "coin") {  
      puntos += 10; // add your own score
      audio.Play ();
      if (PlayerPrefs.GetInt ("MyScore") < puntos)
      PlayerPrefs.SetInt ("MyScore", puntos);
      puntuacion.text = "Puntos: " + puntos.ToString ();
      Destroy (c.gameObject);
   }

}
}

 
 
#9
Buenos dias.
 
Tengo una simple lista de objetos(flechas),el cual cuando aprieto la barra espaciadora va quitando uno a uno las flechas de la lista.
 
Esto va perfecto.Pero mi intención es que también me los quite visualmente osea desde el juego con un disable/delete lo que sea.
 
Pero no veo la manera.
 
Agradecería una ayuda.
 
Gracias
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class quitaflechas : MonoBehaviour
{
public List<GameObject> enemies;
void Awake()
{
   enemies = new List<GameObject>();
   foreach(GameObject enemy in GameObject.FindGameObjectsWithTag("flecha"))
   {
      enemies.Add (enemy);    
   }
}
void Update()
{
   if(enemies.Count > )
   {
      if(Input.GetKeyDown (KeyCode.Space))
      {
         enemies.RemoveAt();
         print (enemies.Count);
      }
   }
}
}

 
 
 
 
#10
General (Antiguo) / Disparo enemigo(resuelto).
Junio 01, 2017, 10:36:48 PM
Buenas noches , tengo un pequeño problema con un disparo que me realiza un enemigo.
 
En este caso es una nave enemiga que al estar en un rango de alcance, me dispara. hasta aquí todo esta bien.
 
El problema viene cuando instancio el láser que me dispara el enemigo....intento que me dispare en intervalos osea que salga por ejemplo 1 laser cada segundo pero me saca 300 lasers seguidos y en linea!!
 
no veo donde fallo para que solo dispare un laser cada por ejemplo 1 segundo.
 
Este es el script:
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemigoataca : MonoBehaviour {
private Transform target;
public int moveSpeed;
public int rotationSpeed;
public int maxRange;
public int minRange;
public GameObject bulletPrefab;
public Transform bulletSpawn;
public float speed;
AudioSource audio;
bool disparo =false;
public float tiempodisparo =0.5f;
private float nextFire =0.0f;
 
private Transform myTransform;
void Awake()
{
   myTransform = transform;
}
void Start ()
{
   GameObject go = GameObject.FindGameObjectWithTag("Player");
   target = go.transform;
}
 
void Update ()
{
   Debug.DrawLine(target.position, myTransform.position, Color.yellow);
   //Look at target
   myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
   if ((Vector3.Distance (transform.position, target.position) < maxRange) && (Vector3.Distance (transform.position, target.position) > minRange))
   {
      transform.LookAt (target);
      transform.Translate (Vector3.forward * moveSpeed * Time.deltaTime);
      Invoke("Fire",3);
   }
}
void Fire()
{
       nextFire = Time.time + tiempodisparo;
   var bullet = (GameObject)Instantiate (bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
       Destroy(bullet, 0.3f);
}
}
 
 

 
Agradecería una ayuda o idea, gracias de antemano!!!
 
 
 
 
 
 
 
 
#11
General (Antiguo) / Trigger exit audio
Abril 22, 2017, 06:51:45 PM
Buenas tardes , tengo un simple script que al entrar en un trigger empiexa a sonar una musica y quiero que al salir se detenga bajando el volumen.
 
No me da error , y suena al entrar...pero no disminuye al salir como yo esperaba.
 
El debug lo marca bien , osea que detecta al jugador al salir.
 
Alguna idea por favor?
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class activaenemigos : MonoBehaviour {
private GameObject player;
public GameObject enemigos;
private GameObject cameramain;
private GameObject cameraenemiga;
float audioVolume;
AudioSource audio;
void Start ()
{
enemigos.SetActive (false);
player = GameObject.FindWithTag ("Player");
audio = GetComponent<AudioSource>();
}
void OnTriggerEnter (Collider col)
{
   if (col.tag == "Player")
   {  
      enemigos.SetActive (true);
      audio.Play ();
   }
}
void OnTriggerExit (Collider col)
{
   Debug.Log ("salida");
   if (audio.volume > 0.09)
   {
      audio.volume -= 0.1f * Time.deltaTime;
   }   
        Invoke ("desactivalos",5);
}
void Update()
{
   if (player.GetComponent<vidajugador> ().curHealth < )
   {
      if (audio.volume > 0.09)
      {
         audio.volume -= 0.1f * Time.deltaTime;
      }
      Invoke ("desactivalos",16);
   }
}
void desactivalos()
{
    enemigos.SetActive (false);
   if (audio.volume > 0.09)
   {
      audio.volume -= 0.1f * Time.deltaTime;
   }
}
}

 
Gracias
#12
General (Antiguo) / Distancia de objetos
Marzo 19, 2017, 02:48:49 PM
Buenas tardes,
 
Tengo una duda y quiero preguntarles:
 
Tengo un sencillo sistema de paga para mi juego el cual simplemente me muestra en una textura de radar los enemigos y los busca por tag,
 
Esto funciona perfectamente el problema viene en la distancia en que los detecta.
 
por mucho que le suba la public float no aumenta la distancia en que me aparecen en el radar y no se el motivo....
 
Allá va el script:
 

using UnityEngine;
using HWRcomponent;
using System.Collections;
 
namespace HWRcomponent
{
public enum Alignment
{
   None,
   LeftTop,
   RightTop,
   LeftBot,
   RightBot ,
   MiddleTop ,
   MiddleBot
}
}
public class RadarSystem : MonoBehaviour
{
private Vector2 inposition;
public float Size = 400; //  tamaño e el mapa
public float Distance = ;// distania maxima de los objetos
public float Transparency = 0.5f;// transparencia de lso objetos
public Texture2D[] Navtexture;// lista de texturs
public string[] EnemyTag;// lista de tags de los objetos
public Texture2D NavCompass;// textura de el compas
public Texture2D CompassBackground;// textura de el fondo
public Vector2 PositionOffset = new Vector2 (, );// posición de el minimapa
public float Scale = 1;// escala de el minimapa
public Alignment PositionAlignment = Alignment.None;// alineamiento
public bool MapRotation;
public GameObject Player;
public bool Show = true;
public Color ColorMult = Color.white;

void Start ()
{

}
void Update ()
{
   if (!Player) {
      Player = this.gameObject;
   }
   
   if (Scale <= ) {
      Scale = 100;
   }
   // define la posición
   switch (PositionAlignment) {
   case Alignment.None:
      inposition = PositionOffset;
      break;
   case Alignment.LeftTop:
      inposition = Vector2.zero + PositionOffset;
      break;
   case Alignment.RightTop:
      inposition = new Vector2 (Screen.width - Size, ) + PositionOffset;
      break;
   case Alignment.LeftBot:
      inposition = new Vector2 (, Screen.height - Size) + PositionOffset;
      break;
   case Alignment.RightBot:
      inposition = new Vector2 (Screen.width - Size, Screen.height - Size) + PositionOffset;
      break;
   case Alignment.MiddleTop:
      inposition = new Vector2 ((Screen.width / 2) - (Size / 2), Size) + PositionOffset;
      break;
   case Alignment.MiddleBot:
      inposition = new Vector2 ((Screen.width / 2) - (Size / 2), Screen.height - Size) + PositionOffset;
      break;
   }
   
}
Vector2 ConvertToNavPosition (Vector3 pos)
{
   Vector2 res = Vector2.zero;
   if (Player) {
      res.x = inposition.x + (((pos.x - Player.transform.position.x) + (Size * Scale) / 2f) / Scale);
      res.y = inposition.y + ((-(pos.z - Player.transform.position.z) + (Size * Scale) / 2f) / Scale);
   }
   return res;
}
void DrawNav (GameObject[] enemylists, Texture2D navtexture)
{
   if (Player) {
      for (int i=; i<enemylists.Length; i++) {
         if (Vector3.Distance (Player.transform.position, enemylists [i].transform.position) <= (Distance * Scale)) {
            Vector2 pos = ConvertToNavPosition (enemylists [i].transform.position);
         
            if (Vector2.Distance (pos, (inposition + new Vector2 (Size / 2f, Size / 2f))) + (navtexture.width / 2) < (Size / 2f)) {
               float navscale = Scale;
               if (navscale < 1) {
                  navscale = 1;
               }
               GUI.DrawTexture (new Rect (pos.x - (navtexture.width / navscale) / 2, pos.y - (navtexture.height / navscale) / 2, navtexture.width / navscale, navtexture.height / navscale), navtexture);
            }
         }
      }
   }
}
float[] list;
void OnGUI ()
{
   if (!Show)
      return;
   
   GUI.color = new Color (ColorMult.r, ColorMult.g, ColorMult.b, Transparency);
   if (MapRotation) {
      GUIUtility.RotateAroundPivot (-(this.transform.eulerAngles.y), inposition + new Vector2 (Size / 2f, Size / 2f));
   }

   for (int i=; i<EnemyTag.Length; i++) {
      DrawNav (GameObject.FindGameObjectsWithTag (EnemyTag [i]), Navtexture [i]);
   }
   if (CompassBackground)
      GUI.DrawTexture (new Rect (inposition.x, inposition.y, Size, Size), CompassBackground);
   GUIUtility.RotateAroundPivot ((this.transform.eulerAngles.y), inposition + new Vector2 (Size / 2f, Size / 2f));
   if (NavCompass)
      GUI.DrawTexture (new Rect (inposition.x + (Size / 2f) - (NavCompass.width / 2f), inposition.y + (Size / 2f) - (NavCompass.height / 2f), NavCompass.width, NavCompass.height), NavCompass);
}
}

 
 
 
Linea 26: public float Distance 0 ;
 
Gracias.
 
 
 
 
 
 
 
 
#13
Buenas tardes,
 
Tengo una duda y no se porque no la puedo solucionar....
 
Tengo un barco que al estar parado/relenti , el sonido es de bajas revoluciones.
 
Al acelerar acelero el pitch de el audioclip(eso funciona no me hace el Time.deltatime) pero funciona.
 
El problema viene cuando decelero.
 
El sonido baja el pitch pero no al numero que yo le doy, solo una coma por debajo.
 
Expongo el scrip asi lo entienden mejor:;
 

using System.Collections;
using UnityEngine;
    public class controlbarco : MonoBehaviour {

public float velocidadgiro = 50f;
public float marcha =50f;
AudioSource audio;
private Rigidbody rb;
public GameObject espuma;
public float decelera = 0.49f;
public float acelera = 1f;
 
void Start()
{
   rb = GetComponent<Rigidbody>();
   espuma.SetActive(false);
   audio = GetComponent<AudioSource>();
   audio.pitch = decelera;
}
void FixedUpdate ()
{
   
   float h = Input.GetAxis ("Horizontal") * velocidadgiro * Time.deltaTime;
   float v = Input.GetAxis ("gatilloderecha") * marcha * Time.deltaTime;
   rb.AddTorque (transform.up * h);
   rb.velocity = transform.forward * v;
            
   if (v >= 0.1f) {
      espuma.SetActive (true);
      if (audio.pitch <= 1f) {      
      audio.pitch += acelera * Time.deltaTime;
      }
   }
   
   if (v <= 0.1f) {
   if (audio.pitch >= acelera)
   {      
   audio.pitch -= decelera *Time.deltaTime;
   Invoke ("paraespumas", 2);
   }
   }
   Debug.Log("Velocity: " + rb.velocity + "//Variable V " + v);
    }
   void paraespumas()
   {
   espuma.SetActive (false);
   {      
   }
   }
}

 
los floats publicos los tengo en :
 
Acelera 1
 
Decelera 0.49
 
El acelera va bien (se pone a 1), porque en el start le tengo que el pitch este en el valor de decelera.
 
El decelera se queda a: 0.99 en vez de los -0.49 que debería quedar.
 
Donde lo estoy haciendo mal?
 
 
 
Muchas gracias por adelantado.
 
 
#14
Buenos dias comunidad.
 
Agradecería si podéis decirme donde estoy fallando y porque...
 
He creado estas 4 lineas de codigo , nada del otro mundo, para mover un objeto adelante y hacia los lados etc con los axis verticales y horizontales,.
 
 
 

using System.Collections;
using UnityEngine;
    public class controlbarco : MonoBehaviour {

public float velocidadgiro=0f;
public float marcha=0f;
float startY;
private Rigidbody rb;
void Start()
{
   rb = GetComponent<Rigidbody>();

}
void Update () {
   
float girar =Input.GetAxis("Horizontal");
float adelante =Input.GetAxis("gatilloderecha");
   
rb.AddTorque(transform.up*velocidadgiro*girar*Time.deltatime);
rb.AddForce(transform.forward*adelante*marcha*Time.deltatime);
   
    }
    }

 
bien, la idea era que girara / acelerara a una velocidad paulatina osea con el Time.deltatime hasta alcanzar el valor de el float correspondiente.
 
Pues no. no se mueve en absoluto , en cambio si le quito los Time.....si se mueve pero alcanza la velocidad tanto de giro como de marcha de golpe  y sigue acelerando sin parar! de acelerar asi;:
 

rb.AddTorque(transform.up*velocidadgiro*girar);
rb.AddForce(transform.forward*adelante*marcha);

 
Y la pregunta es:
 
Que estoy haciendo mal :)
 
No da error..
 
Gracias de antemano!!!
 
 
#15
Muy buenas tardes, he retomado Unity después de un letargo....y creo que me he oxidado...
 
Según lo que sabia esto deberia funcionar, pero por al guna razón se me olvida algo que no se que es.
 
Tengo dos GO(Gameobjects), uno con rigid t triger y collider y el otro con collider sin triguer.
 
En uno tengo este script:
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class tiempodinero : MonoBehaviour {
public static float totaldinero = 400f;
public Text dinero;
void Start () {
dinero.text=string.Format ("{0}","$"+totaldinero);
}
}

 
bien funciona perfectamente y se muestra en pantalla el valor de 400.
 
Ahora en el otro objeto tengo que restarle 50 al valor de 400 al entrar en contacto(triggerenter) y lo pongo asi:
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class restadinero : MonoBehaviour {
void OnTriggerEnter(Collider other)
{
   if (other.tag == "gas")
   {
      Debug.Log("tocado");
      tiempodinero.totaldinero -= 50f;
   
   }
}
}

 
Bien esto deberia restar 50 al 400....unity no me da error ni nada, pero, no me resta el valor.
 
Ni que decir tiene que los tags están al dia.
 
Agradecería una pequeña ayuda/sugerencia.
 
Gracias de antemano.
 
 
 
 
 
 
 
 
 
 
#16
General (Antiguo) / Configurable Joint...
Febrero 18, 2017, 12:42:42 AM
Buenas noches a todos, agradecería una ayuda o sugerencia de como desactivar un Configurable Joint...
 
Como bien sabemos(i si no lo saben aquí lo expongo), el dichoso no lleva el tipico cuadradito de desactivame.
 
Bien la cosa es que el Enabled o el Setactive tampoco lo desactivan....
 
Y direis para que lo quiero desactivar, bien , pues sencillo , tengo un camion de carga que al acercarse al trailer se engancha a el ,y asi es pero no hay quien lo despegue de allí , la manera correcta seria desactivando dicho...Joint.
 
 
 
Agradecería una luz.
 
Muchas gracias de antemano.
 
P.D el Configurable joint esta en el remolque y lleva el body de el camión que lo arrastra.
 
 
#17
General (Antiguo) / contoles xbox 360
Septiembre 23, 2016, 02:46:02 PM
Buenas tardes, me estoy volviendo loco para poder usar el controlador de Xbox 360 con el movimiento de este caballo....
 
el Script esta para que se mueva con las teclas w,s.a.d o con las arrow, pero quiero mapearlo a el controlador de xbox....
 
Ya tengo puestos en el input todos los posibles axis, botones etc...
 
Pero ahora me encientro que no veo la manera de aplicarlos para que se mueva con ellos....
 
 
 
Agradecería una ayuda por favor.
 
Adjunto todo el script aunque no creo que aga falta pero para facilitar ;
 
 
 

using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;
 
[RequireComponent(typeof(HashIDs))]
public class HorseController : MonoBehaviour
{
    public enum HorseMeshType
    {
        Horse1 = , Horse2 = 1, BigHorse = 2, PolyArt = 3, MineCraft = 4, Custom = 5
    }
    //float normalizedtime;
    #region Variables
    #region Connection with Rider Variables
    [Tooltip("Enable this if you want to control the horse alone, without requiring mounting")]
    public bool PlayerControlled;
    [Tooltip("This activate the animator layer that contains the horse's bones offset, in order to use the same animation. Custom is for use your own Horse Model")]
    public HorseMeshType horseType;
    [HideInInspector]
    public bool Mounted;
    [HideInInspector]
    public bool Mountedside;
    [HideInInspector]
    public Animator RiderAnimator; // Rider's Animatorto control both Sync animators from here
    #endregion
    #region Horse Components
    private Animator anim;
    private Rigidbody horseRigidBody;
    private BoxCollider horseCollider;
    private HashIDs hashs;  //Hash ID For the animator parameters
    private float scaleFactor;
    #endregion
    #region Animator Parameters Variables
    private float speed;
    private float direction;
    private float MaxSpeed = 1f; //1 Walking, 2 Trotting, 3 Cantering, 4 Galloping, 5 Sprinting
 
    //States Variables
    private bool
        galoping,
        trotting,
        swimming,
        flying, // Coming Soon Pegassus
        falling,
        fallingback,
        sleep,
        jump,
        Shift, //Cantering ,Sprint, turn 180
        attack,
        IsInWaterHip,
        IsInWater,
        stand,
        fowardPressed = false;
 
    private int sleepCount, horseInt;
    private float horizontal, vertical, horsefloat = , MaxHeight;
    private float jumpingCurve;
    #endregion
 
    [Header("Custom Options")]
    [Tooltip("Add more rotation to the turn animations")]
    [Range(, 100)]
    public float TurnSpeed = 5;
    [Tooltip("Amount of idle cycles before go to sleep state")]
    [Range(1, 100)]
    public int GoToSleep = 10;
    [Tooltip("Max Distance for the horse to recover from a big fall, Greater value: The horse will still running after falling from a great height")]
    [Range(1, 100)]
    public float recoverByFallDist;
    [Tooltip("Smoothness for snapping to ground, Higher value Harder Snap")]
    [Range(1, 100)]
    public float SnapToGround = 20f;
 
    [Header("Swim Options")]
    [Range(1, 10)]
    public float swimSpeed = 1f;
    [Range(1, 100)]
    public float SwimTurnSpeed = 1f;
 
    #region FixTransform_Variables
    RaycastHit hit_Hip, hit_Chest, WaterHitCenter;
    Vector3 Horse_Hip, Horse_Chest;
    Vector3 ErrorTresh = Vector3.up * 0.5f;
    float distanceHip;
    const float fallingMultiplier = 1.6f;
    float heightHorse;
    float WaterDistanceHip, distanceChest;
    float angleTerrain, inclination, fallheight;
    Pivots[] pivots;
    private Vector3 ColliderCenter;
    private Vector3 rigidVelocity;
    #endregion
    [Header("Keys for Horse Speed")]
    public KeyCode Walk = KeyCode.Alpha1;
    public KeyCode Trot = KeyCode.Alpha2;
    public KeyCode Gallop = KeyCode.Alpha3;
    [Header("Reference For Rider IKs Points")]
    #region Transform feet and mount on the Horse
    public Transform RidersLink;   // Reference for the RidersLink Bone
    public Transform LeftIK;       // Reference for the LeftFoot correct position on the mount
    public Transform RightIK;      // Reference for the RightFoot correct position on the mount
    public Transform LeftKnee;     // Reference for the LeftKnee correct position on the mount
    public Transform RightKnee;    // Reference for the RightKnee correct position on the mount
    #endregion
    #endregion
    #region Properies      
    public bool Stand
    {
        get { return this.stand; }
    }
    public float MaxFallHeight
    {
        set { fallheight = value; }
        get { return this.fallheight; }
    }
    public bool Sleep
    {
        set { sleep = value; }
    }
    public int SleepCount
    {
        set { sleepCount = value; }
        get { return this.sleepCount; }
    }
    public bool isFalling
    {
        // set { falling = value; }
        get { return this.falling; }
    }
    public int HorseInt
    {
        set { horseInt = value; }
        get { return this.horseInt; }
    }
    public float HorseFloat
    {
        set { horsefloat = value; }
        get { return this.horsefloat; }
    }
    #endregion
 
    // Use this for initialization
    void Start()
    {
       // Cursor.visible = false;
        anim = GetComponent<Animator>();
        hashs = GetComponent<HashIDs>();
       
        horseCollider = GetComponent<BoxCollider>();
        horseRigidBody = GetComponent<Rigidbody>();
        ColliderCenter = horseCollider.center;
        pivots = GetComponentsInChildren<Pivots>(); //Pivots are Strategically Transform objects use to cast rays used by the horse
        scaleFactor = transform.localScale.y;  //TOTALLY SCALABE HORSE
 
        heightHorse = pivots[].transform.localPosition.y * scaleFactor; // Height from Chest to ground
        anim.SetInteger("HorseType", (int)horseType); //Adjust the layer for the curret horse Type
        horseRigidBody.drag = ;
        horseRigidBody.angularDrag = 25f;
        sleepCount = ;
        //
    }
    //----------------------Link the buttons pressed with correspond variables-------------------------------------------------------------------------------
    void getButtons()
    {
        fowardPressed = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow); //If foward is pressed
        #if UNITY_ANDROID || UNITY_IOS
                if (CrossPlatformInputManager.GetAxis("Vertical") > )
                    fowardPressed = true;
                else fowardPressed = false;
        #endif
        attack = CrossPlatformInputManager.GetButtonDown("Fire1");            //Get the Attack button
        if (attack)
        {
            horseInt = Random.Range(, 3);                                         //Random Attack ID: ID identify the type of attack
            sleepCount = ;
        }
 
        horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
        vertical = CrossPlatformInputManager.GetAxis("Vertical");
        Shift = CrossPlatformInputManager.GetButton("Fire3");
       // Shift = Input.GetKey(KeyCode.LeftShift);
       
        #if UNITY_ANDROID || UNITY_IOS
         
        #endif
        //Get the Sprint/Cantering/Turn180 button
        jump = CrossPlatformInputManager.GetButtonDown("Jump");             //Get the Jump button
        if (Input.GetKeyDown(KeyCode.K))                                    //Get the Death button
        {
            horseInt = Random.Range(, 2);
        }
    }
    //----------------------linking  the Parameters Horse && Rider------------------------------------------------------------------------
    void LinkingAnimator(Animator anim_)
    {
        jumpingCurve = anim.GetFloat("JumpCurve");
        anim_.SetFloat(hashs.speedHash, speed*vertical);
        anim_.SetFloat(hashs.horizontalHash, direction);
        anim_.SetBool(hashs.shiftHash, Shift);
        anim_.SetBool(hashs.galopingHash, galoping);
        anim_.SetBool(hashs.trottingHash, trotting);
        anim_.SetBool(hashs.standHash, stand);
        anim_.SetBool(hashs.jumpHash, jump);
        anim_.SetBool(hashs.fowardHash, fowardPressed);
        anim_.SetBool(hashs.SwimHash, swimming);
        anim_.SetFloat(hashs.inclinationHash, inclination);
        anim_.SetBool(hashs.fallingHash, falling);
        anim_.SetBool(hashs.fallingBackHash, fallingback);
        anim_.SetBool(hashs.sleepHash, sleep);
        anim_.SetBool(hashs.attackHash, attack);
        anim_.SetInteger(hashs.IntHash, horseInt);
       
        if (falling || isJumping(1,true))
        {
            anim_.SetFloat(hashs.FloatHash, horsefloat);
        }
        if (Input.GetKeyDown(KeyCode.K))
        {
            anim_.SetTrigger(hashs.deathHash);
        }
 
    }
    //--Add more Rotations to the current turn animations  using the public turnSpeed float--------------------------------------------
    void TurnAmount()
    {
        //For going Foward and Backward
        if (vertical >= )
        {
           
            if (!swimming)
                transform.Rotate(transform.up, TurnSpeed * 3 * horizontal * Time.deltaTime);
            else
                transform.Rotate(transform.up, SwimTurnSpeed * 3 * horizontal * Time.deltaTime);
            //horseRigidBody.AddTorque((transform.up * horizontal) * TurnSpeed / 2 / Time.deltaTime);
        }
        else
        {
            if (!swimming)
            {
                transform.Rotate(transform.up, TurnSpeed * 3 * -horizontal * Time.deltaTime);
            }
            else
            {
                transform.Rotate(transform.up, SwimTurnSpeed * 3 * -horizontal * Time.deltaTime);
            }
            // horseRigidBody.AddTorque((transform.up * -horizontal) * TurnSpeed / 2 / Time.deltaTime);
        }
        //Add Speed to current animation foward swim
        if (swimming && vertical>)
        {
            transform.position = Vector3.Lerp(transform.position, transform.position + transform.forward * swimSpeed * vertical/2, Time.deltaTime);
        }
    }
 
    //--------The Collider is not touching the floor to avoid collision with small objects, Here the Height is fixed , Terrain Compatible----------
    void FixPosition()
    {
        //Position to cast a ray downward from the  Horse Chest and Horse Hip.
        Horse_Hip = pivots[].transform.position;
        Horse_Chest = pivots[1].transform.position;
        inclination = ((Horse_Chest.y - Horse_Hip.y) / 2) / scaleFactor;  //Calculate the inclination between front and rear legs\
        Vector3 JumpingCurve = new Vector3(, jumpingCurve, );
        //Ray From Horse Hip to the ground
        if (Physics.Raycast(Horse_Hip + JumpingCurve, -transform.up, out hit_Hip, (heightHorse + jumpingCurve) * fallingMultiplier * scaleFactor, LayerMask.GetMask("Default")))
        {
            Debug.DrawRay(Horse_Hip + JumpingCurve, -transform.up * heightHorse * scaleFactor * fallingMultiplier, Color.green);
            distanceHip = hit_Hip.distance - jumpingCurve;
        }
        else
        {
            fallingback = true;
        }
 
        //Ray From Horse Chest to the ground
        if (Physics.Raycast(Horse_Chest + JumpingCurve, -transform.up, out hit_Chest, (heightHorse + jumpingCurve) * fallingMultiplier * scaleFactor, LayerMask.GetMask("Default")))
        {
            distanceChest = hit_Chest.distance - jumpingCurve;
            Debug.DrawRay(Horse_Chest + JumpingCurve, -transform.up * heightHorse * scaleFactor * fallingMultiplier, Color.green);
        }
        else
        {
           falling = true;
           
        }
 

        //Front RayWater Cast
        if (Physics.Raycast(horseCollider.bounds.center + ErrorTresh+ JumpingCurve, -transform.up, out WaterHitCenter, heightHorse * scaleFactor*2, LayerMask.GetMask("Water")))
        {
            Debug.DrawRay(horseCollider.bounds.center + ErrorTresh + JumpingCurve, -transform.up * heightHorse * scaleFactor * 2, Color.blue);
           
            //if there nothing on top of the water
            if (hit_Chest.distance>WaterHitCenter.distance)
            {
                IsInWater = true;
            }
        }
        else
        {
            IsInWater = false;
        }
 

        //If the horse has  water near the Neck then start swimming
        if (WaterHitCenter.transform) //if we hit water
        {
            if (Horse_Chest.y < WaterHitCenter.transform.position.y && IsInWater)
            {
                swimming = true;
                falling = false;
            }
            if (IsInWater && distanceChest < 1f * scaleFactor)  //else stop swimming when he is coming out of the water
            {
               swimming = false;
               MaxSpeed = 1f;
               galoping = false;
               trotting = false;
            }
        }
 
        //-----------------------------water Adjusment-------------------------------------------
        if (swimming)
        {
            falling = false;
            fallingback = false;
            horseRigidBody.constraints = RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezePositionY;
            float angleWater = Vector3.Angle(transform.up, Vector3.up);
            Quaternion finalRot = Quaternion.FromToRotation(transform.up, Vector3.up) * horseRigidBody.rotation;
            //Smoothy rotate until is Aling with the Water
            if (angleWater > 0.1f)
                transform.rotation = Quaternion.Lerp(transform.rotation, finalRot, Time.deltaTime * 10);
            else
                transform.rotation = finalRot;
            //Smoothy Move until is Aling with the Water
            if (WaterHitCenter.transform)
                transform.position = Vector3.Lerp(transform.position, new Vector3(transform.position.x, WaterHitCenter.transform.position.y - heightHorse, transform.position.z), Time.deltaTime * 5f);
        }
        else
        {
            //------------------------------------------------Terrain Adjusment-----------------------------------------
            //----------Calculate the Align vector of the terrain------------------
            Vector3 direction = (hit_Chest.point - hit_Hip.point).normalized;
            Vector3 Side = Vector3.Cross(Vector3.up, direction).normalized;
            Vector3 SurfaceNormal = Vector3.Cross(direction, Side).normalized;
            angleTerrain = Vector3.Angle(transform.up, SurfaceNormal);
            // ------------------------------------------Orient To Terrain-----------------------------------------  
            Quaternion finalRot = Quaternion.FromToRotation(transform.up, SurfaceNormal) * horseRigidBody.rotation;
            // If the horse is falling smoothly aling with the horizontal
            if ((isJumping(0.55f, true)) || fallingback)
            {
                finalRot = Quaternion.FromToRotation(transform.up, Vector3.up) * horseRigidBody.rotation;
                transform.rotation = Quaternion.Lerp(transform.rotation, finalRot, Time.deltaTime * 5f);
            }
            else
            {
                // if the terrain changes hard smoothly adjust to the terrain
                if (angleTerrain > 2 && !stand)
                {
                    transform.rotation = Quaternion.Lerp(transform.rotation, finalRot, Time.deltaTime * 10f);
                }
                else
                {
                    transform.rotation = finalRot;
                }
            }
            float distance = distanceHip;
            float realsnap = SnapToGround; // changue in the inspector the  adjusting speed for the terrain
            if (isJumping(0.5f, false)) //Calculate from the front legss
            {
                //calculate the adjust distance from the front legs if is finishing jumping. Solution for jumping High places at the same distance
                 distance = distanceChest;
                realsnap = SnapToGround / 4;
            }
            //-----------------------------------------Snap To Terrain-------------------------------------------
            if (distance != heightHorse)
            {
                float diference = heightHorse - distance;
                transform.position = Vector3.Lerp(transform.position, transform.position + new Vector3(, diference, ), Time.deltaTime * realsnap);
            }
        }
    }
    public void Falling()
    {
        //if the horse stay stucked while falling move foward  ... basic solution
        if (falling && horseRigidBody.velocity.magnitude<0.1 && !swimming)
        {
            transform.position = Vector3.Lerp(transform.position, transform.position + transform.forward*2, Time.deltaTime);
        }
 
        RaycastHit offGround; //Front Falling Ray
        Vector3 FallingVectorFront = pivots[2].transform.position; // get the Transform Falling from vector within the horse hierarchy
        Debug.DrawRay(FallingVectorFront, -transform.up * heightHorse * fallingMultiplier, Color.blue);
        //Ignore Layer Horse 20
        var layermask = 1 << 20;
        layermask = ~layermask;
        if (Physics.Raycast(FallingVectorFront, -transform.up, out offGround, heightHorse * fallingMultiplier,layermask))
        {
            //---------------------Finding the water while falling------------------------
            if (offGround.transform.gameObject.layer == 4) //4 is Water layer
            {
                if (offGround.transform) //if we hit water
                {
                    IsInWater =
#18
General (Antiguo) / Reiniciar un nivel.
Septiembre 01, 2016, 05:20:36 PM
Buenas tardes, tengo un pequeño y espero decir pequeño porque seria una ***a...problemilla.
 
Tengo un proyecto de juego que solo tiene una escena.
 
Bien si la palmas te sale el típico botón reiniciar.
 
bien el juego empieza de nuevo pero....algunos scripts o componentes no reaccionan / funcionan adecuadamente como si se cargaran mal.Estoy usando el ultimo Unity y creo que he probado todas las maneras de reiniciar el nivel:
 

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class gameover : MonoBehaviour {
 

public void reiniciar()
{
//SceneManager.LoadScene("mesapinball"); ////ESTA NO VA BIEN
//   Application.LoadLevel (Application.loadedLevelName);//ESTA TAMPOCO....
SceneManager.LoadScene(SceneManager.GetActiveScene().name);///TAMPOCO
Time.timeScale = 1.0F;
}
   
public void salir()
{
Application.Quit();
}
}

 
todas lo reinician pero omitiendo trozos....debería meter un dontdestroy a todo lo que no funciona?
 
 
 
Sabéis de otra manera para que se cargue todo?
 
EDITO;
 
el que no se carga de nuevo al hacer el restart es peculiarmente este:
 

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class droptargetss : MonoBehaviour {
public float dropDistance = 1.0f;
public int bankID = ;
public float resetDelay = 0.5f;
public static List<droptargetss> dropTargets = new List<droptargetss>();
public int targetValue = 100;
public int bankValue = 10000;
AudioSource audio;
public AudioClip sonidotarget;   
public AudioClip cantina;   
public bool isDropped = false;
public GameObject luzx1;
public GameObject luzx2;
public  GameObject TextOnSpotGO;
//public GameObject cantinavideo;
 
//   void Awake() {
//      DontDestroyOnLoad(transform.gameObject);
//   }
// Use this for initialization
void Awake ()
{
   dropTargets.Add(this);
   audio = GetComponent<AudioSource>();
   luzx2.SetActive (false);
}
// Update is called once per frame
void Update ()
{
}
void OnCollisionEnter()
{
   if(!isDropped)
   {
      //Drop Target
      transform.position += Vector3.down*dropDistance;
      isDropped = true;
      ScoreManager.Instance.ScoreUp(targetValue);
      GameObject textInstance = Instantiate (TextOnSpotGO, transform.position, Quaternion.identity) as GameObject;
      textInstance.GetComponent<TextOnSpotScript>().DisplayText = targetValue * ScoreManager.Instance.scorePower + "";
      //         ScoreManager.Instance.ScoreUp(targetValue);
      //         //ScoreManager.Instance.ScoreUp(scoreValue);
      //         Instantiate (TextOnSpotGO, transform.position, Quaternion.identity);
      //         TextOnSpotGO.GetComponent<TextOnSpotScript>().DisplayText = ScoreManager.Instance.scoretarjets * ScoreManager.Instance.scorePower + "";
      audio.PlayOneShot(sonidotarget, 0.7F);
 
      //Check to see if the rest of the bank has been dropped
      bool resetBank = true;
      foreach(droptargetss target in dropTargets)
      {
         if(target.bankID == bankID)
         {
            if(!target.isDropped)
            {
               resetBank = false;
            }
         }
      }
      //Reset all drop targets in bank if the bank has been dropped
      if(resetBank)
      {
         //ScoreManager.Instance.score += bankValue;
         ScoreManager.Instance.ScoreUp(bankValue);///(scoreValue);
         Instantiate (TextOnSpotGO, transform.position, Quaternion.identity);
         TextOnSpotGO.GetComponent<TextOnSpotScript>().DisplayText = ScoreManager.Instance.bankvalue * ScoreManager.Instance.scorePower + "";
         Invoke("ResetBank", resetDelay);
         ScoreManager.Instance.SetScorePower (2);
         audio.PlayOneShot(cantina, 0.7F);
         //cantinavideo.SetActive (true);
         luzx2.SetActive (true);
         luzx1.SetActive (false);
      }
   }
}
void ResetBank()
{
   foreach(droptargetss target in dropTargets)
   {
      if(target.bankID == bankID)
      {
         target.transform.position += Vector3.up*dropDistance;
         target.isDropped = false;
      }
   }
}
}

 
Alguna idea?
 
He probado con dont destroy pero al reiniciar el nivel se duplica...
 
 
 
 
 
 
 
 
 
 
#19
General (Antiguo) / Añadir +1 a un int...
Agosto 29, 2016, 01:45:42 PM
Buenas tardes
 
Tengo un problema con un int que aprenetemente es facul pero me lleva de cabeza.
 
Quiero añadir +1 a un public int en este caso numero de bolas al llegar a una puntuación...pues no hay manera.
 
Este script alberga el numero de bolas:
 

using UnityEngine;
using System.Collections;
public class BallManager : MonoBehaviour
{
public GameObject ball;
public Transform spawnPosition;
public TextMesh display;
public int lives = 3;
public bool gameOver = false;
AudioSource audio;
public GameObject luzx1;
public GameObject luzx2;
public GameObject luzx3;
 
   
void Update()
{
   AudioSource audio = GetComponent<AudioSource> ();
   //Check for gameover
   if (lives < ) {
      if (display) {
         display.text = "GAME OVER";
         gameOver = true;
      }
   }
   
   //Ball cae y no es game over
   if (!GameObject.FindGameObjectWithTag ("Ball") && !gameOver) {
      lives--;
      Instantiate (ball, spawnPosition.position, ball.transform.rotation);
      audio.Play ();
      luzx1.SetActive (true);
      luzx2.SetActive (false);
      luzx3.SetActive (false);
      ScoreManager.Instance.SetScorePower (1);
      //Update bolas restantes
      if(display)
      {
         display.text = "BOLAS RESTANTES: " + lives.ToString();
      }
   }
   
   if(gameOver)
   {
      if(Input.GetKeyDown(KeyCode.Return))
      {
         Application.LoadLevel(Application.loadedLevel);
      }
   
   }
}
}

 
Este es el que intento que añada una bola extra al llegar a xxxx puntos.
 

using UnityEngine;
using System.Collections;
public class ScoreManager : MonoBehaviour
{
public static ScoreManager Instance;
void Awake()
{
Instance = this;
}
public   int score =;
public   int scorebumper =50000;
public   int scoredianas =100;
public   int scoreagujeros =10000;
public   int scoretarjets =100;
public   int scorePower = 2;
public   int bankvalue =10000;
public    TextMesh display;
public GameObject Ballmanager;
private bool detener;
 
void Update()
{
   if (display)
   {
      display.text = score.ToString ("D8");
   }
   if (score == 10000 && detener == false) {
   Invoke("millonn",1);
}   
}
public   void ScoreUp(int points)
{
score += (points * scorePower);
}
public  void SetScorePower(int power)
{
   scorePower = power;
}
void millonn()
{
Debug.Log ("MILLLOOOOONNN");
   Ballmanager.GetComponent<BallManager> ().lives =+3 ;
}
}

 
Pues no hay manera me aumenta las 3 bolas...pero si me queda una bola antes de llegar a la puntuación me suma las 3.... si le pongo +1 me deja en 1....agradeceria un aire a este problema , 
 
Gracias de antemano y un saludo.
 
 
#20
General (Antiguo) / Rotación objecto
Agosto 28, 2016, 01:47:21 AM
Buenas noches, una pregunta por favor.
 
Necesito que una plataforma de vueltas cuando algo se le choca.
 
 si le añado esto:
 

public float speed;
transform.Rotate(20,*Time.deltaTime*speed,);

 
Gira sin problemas sobre su axis.
 
Pero si le añado la colisión:
 

using UnityEngine;
using System.Collections;
public class gira : MonoBehaviour {
public float speed;
//public float time;
 
void OnCollisionEnter(Collision collision){
   
   foreach (ContactPoint contact in collision.contacts) {
   transform.Rotate(20,*Time.deltaTime*speed,);
  }
}
}

 
Gira pero se detiene en el primer segundo de el time.deltatime.
 
Probé con trigger en vez de collision y el resultado es el mismo.
 
Probé añadiendo un float tiempo pero hace caso omiso...
 
Agradeceria una idea.
 
Gracias