unity - android touch button with name fire1 not working - c#

i need help to fix the following code to be able fire when bullet when touch the fire 1 button its not working when i use unity remote on my mobile
steps
Assined the PlayerShoot script to GameObject
click on the button in the scene, go to the inspector. and add an OnClick event, drag the gameobject that has the script on it, and select the Fire() function.
using the unity remote app on mobile where the fire button not working
the code i use ...as the following :
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerShoot : MonoBehaviour {
public GameObject Ammo; // the shot
GameObject FiredShot;
public AudioClip bcgMusic;
public List<GameObject> ShotsOnAir;
//public AudioClip sound1; // Use this for initialization
void Start (){
ShotsOnAir = new List<GameObject>();
}
//void Update (){
// Fire ();
//}
public void Fire(){
if (Input.GetButtonDown ("Fire1")){
FiredShot = (GameObject)Instantiate(Ammo,transform.position,transform.rotation);
ShotsOnAir.Add(FiredShot);
AudioSource.PlayClipAtPoint (bcgMusic, transform.position);
}
if(ShotsOnAir != null){
int i=0;
foreach (GameObject GB in ShotsOnAir){
ShotsOnAir[i].transform.position += ShotsOnAir[i].transform.forward * 200 * Time.deltaTime;
i++;
}
}
}
}

Input.GetButton() does not work on mobile
You need to use Input.touches/Input.GetTouch() instead

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerShoot : MonoBehaviour {
public GameObject Ammo; // the shot
public GameObject FiredShot;
public AudioClip bcgMusic;
public List<GameObject> ShotsOnAir;
//public AudioClip sound1; // Use this for initialization
void Start (){
ShotsOnAir = new List<GameObject>();
}
//void Update (){
// Fire ();
//}
public void Fire(){
//if (Input.touches ("Fire1")){
if (Input.touchCount > 0 ){
FiredShot = (GameObject)Instantiate(Ammo,transform.position,transform.rotation);
ShotsOnAir.Add(FiredShot);
AudioSource.PlayClipAtPoint (bcgMusic, transform.position);
}
if(ShotsOnAir != null){
int i=0;
foreach (GameObject GB in ShotsOnAir){
ShotsOnAir[i].transform.position += ShotsOnAir[i].transform.forward * 10000 * Time.deltaTime;
i++;
}
}
}
}

Related

C# Unity 2D Topdown Movement Script not working

I have been working on a unity project where the player controls a ship. I was following along with a tutorial and have made an input script and a movement script that are tied together with unity's event system. As far as I can tell my script and the script in the tutorial are the same, but the tutorial script functions and mine doesn't.
Script to get player input
using UnityEngine;
using System.Collections;
using System;
using UnityEngine.Events;
public class PlayerInput : MonoBehaviour
{
public UnityEvent<Vector2> OnBoatMovement = new UnityEvent<Vector2>();
public UnityEvent OnShoot = new UnityEvent();
void Update()
{
BoatMovement();
Shoot();
}
private void Shoot()
{
if(Input.GetKey(KeyCode.F))
{
OnShoot?.Invoke();
}
}
private void BoatMovement()
{
Vector2 movementVector = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
OnBoatMovement?.Invoke(movementVector.normalized);
}
}
Script to move player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class Movement : MonoBehaviour
{
public Rigidbody2D rb2d;
private Vector2 movementVector;
public float maxspeed = 10;
public float rotatespeed = 50;
private void Awake()
{
rb2d = GetComponent<Rigidbody2D>();
}
public void HandleShooting()
{
Debug.Log("Shooting");
}
public void Handlemovement(Vector2 movementVector)
{
this.movementVector = movementVector;
}
private void FixedUpdate()
{
rb2d.velocity = (Vector2)transform.up * movementVector.y * maxspeed * Time.deltaTime;
rb2d.MoveRotation(transform.rotation * Quaternion.Euler(0, 0, -movementVector.x * rotatespeed * Time.fixedDeltaTime));
}
}
Any help would be appreciated!
You need to attach your Handlers (HandleShooting and Handlemovement) to corresponding events. Easiest way would be to make events static in PlayerInput
public static UnityEvent<Vector2> OnBoatMovement = new UnityEvent<Vector2>();
public static UnityEvent OnShoot = new UnityEvent();
and attach corresponding handlers to them in Movement.Awake
private void Awake(){
rb2d = GetComponent<Rigidbody2D>();
PlayerInput.OnBoatMovement += Handlemovement;
PlayerInput.OnShoot += HandleShooting;
}
Also in PlayerInput.BoatMovement you should probably check
if(movementVector.sqrMagnitude > 0){
OnBoatMovement?.Invoke(movementVector.normalized);
}
Or else random shit may happen when trying to normalize Vector with magnitude 0 (I compare sqr magnitude to aviod calculating root which is never desired)

I want to make my unity gun script for vr be automatic, any way to do it with this script?

I want it so that if my player holds down the fire button, the gun will be automatic firing so that if I hold the trigger the gun will keep shooting, any way to do that (with fire rate) with this script?
On my image the top is my XR grab interactable.
The button I use to fire is my trigger.
XR grab interactable on top, gun script on bottom
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
public float speed = 40;
public GameObject bullet;
public Transform barrel;
public AudioSource audioSource;
public AudioClip audioClip;
public void Fire()
{
GameObject spawnedBullet = Instantiate(bullet, barrel.position, barrel.rotation);
spawnedBullet.GetComponent<Rigidbody>().velocity = speed * barrel.forward;
audioSource.PlayOneShot(audioClip);
Destroy(spawnedBullet, 2);
}
}
In your case you already have to events: OnActivate and OnDeactivate so you could modify your code like this
public class Gun : MonoBehaviour
{
public float speed = 40;
public GameObject bullet;
public Transform barrel;
public AudioSource audioSource;
public AudioClip audioClip;
// configure shots per second
public float rate = 1;
private Coroutine _current;
public void BeginFire()
{
if(_current != null) StopCoroutine(_current);
_current = StartCoroutine (FireRoutine ());
}
public void StopFire()
{
if(_current != null) StopCoroutine(_current);
}
private IEnumerator FireRoutine()
{
while(true)
{
GameObject spawnedBullet = Instantiate(bullet, barrel.position, barrel.rotation);
spawnedBullet.GetComponent<Rigidbody>().velocity = speed * barrel.forward;
audioSource.PlayOneShot(audioClip);
Destroy(spawnedBullet, 2);
yield return new WaitForSeconds (1f / rate);
}
}
}
And then as so far in OnActivate call the BeginFire and in the OnDeactivate call the StopFire

I'm trying to change var value in one script from another in c# in unity

I have two scripts button.cs attached to Start button object and with flag var in it. And Restart.cs attached to RestartButton object. I'm trying to change bool flag from Button.cs in Restart.cs.
And I get this error:
Assets\Scripts\Restart.cs(14,63): error CS0122: 'Button.flag' is inaccessible due to its protection level
This is button.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Button : MonoBehaviour
{
// Start is called before the first frame update
public GameObject m_cube, obeme, resetButton;
public AudioSource audioSource;
public bool flag = false;
void OnMouseDown(){
if (!flag)
{
flag = true;
transform.localRotation = Quaternion.Euler(0, 0, 180);
m_cube.GetComponent <Animation> ().Play ("cubeGoDown2");
audioSource.Play();
obeme.GetComponent <Animation> ().Play ("obemeGetIn");
resetButton.GetComponent <Animation> ().Play ("RestartButtonGetIn");
}
}
}
And this is Restart.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Restart : MonoBehaviour
{
// Start is called before the first frame update
public GameObject resetButton;
void OnMouseDown()
{
transform.localRotation = Quaternion.Euler(0, 0,0);
GameObject.Find("Start button").GetComponent<Button>().flag = false;;
resetButton.GetComponent <Animation> ().Play ("RestartButtonGetOut");
}
}
The button class Start Button is a preDefined string for unity. so i suggest one of two things.
first: //create a straight reference from your reset to your start button
//like this
//Variables
public GameObject myStartButton;
public GameObject resetButton;
void OnMouseDown()
{
transform.localRotation = Quaternion.Euler(0, 0,0);
myStartButton.flag = false;
resetButton.GetComponent <Animation> ().Play ("RestartButtonGetOut");
}
or just easily make the name unique.

Having problems with "OnCollisionEnter2D" in Unity2D

I'm using this code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CollisionPlayer : MonoBehaviour
{
public bool alreadyDied = false;
public GameObject player;
public float timeDeath;
public ParticleSystem particles;
public GameObject explosionGO;
private SpriteRenderer sr;
private BoxCollider2D bc;
private PlayerController walkScript;
void Start()
{
sr = GetComponent<SpriteRenderer>();
bc = GetComponent<BoxCollider2D>();
walkScript = GetComponent<PlayerController>();
}
void OnCollisionEnter2D (Collision2D collide)
{
if (collide.gameObject.CompareTag("Dead"))
{
Instantiate(particles, player.transform.position, Quaternion.identity);
Instantiate(explosionGO, player.transform.position, Quaternion.identity);
CinemachineShake.Instance.ShakeCamera(30f, .1f);
alreadyDied = true;
}
}
void Update()
{
if(alreadyDied == true)
{
timeDeath -= Time.deltaTime;
sr.enabled = false;
bc.enabled = false;
walkScript.enabled = false;
}
if(timeDeath <= 0)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
}
This is the bullet's code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LeftBulletScript : MonoBehaviour
{
// Start is called before the first frame update
public float speed;
public float destructionLeftTime;
public ParticleSystem particles;
private GameObject thisGameObject;
void Start()
{
thisGameObject = this.gameObject;
Destroy(gameObject, destructionLeftTime);
}
void Update()
{
transform.Translate(Vector2.left * speed * Time.deltaTime);
if(destructionLeftTime > 0.05f)
{
destructionLeftTime -= Time.deltaTime;
}
else
{
Instantiate(particles, thisGameObject.transform.position, Quaternion.identity);
}
}
}
This code should spawn some particles and a sound effect when the player gets hit by something with tag "Dead". But that does not happen. I have a box collider 2D on both the bullet (that should kill me) and the player. My Rigidbody2D is dynamic on the player with z freezed. The bullet does not have a rigidbody. I made sure that the bullet actually has the tag "Dead", spelled the exact same way as the way I wrote on the script. The weirdest thing is that I used this code on another game and nothing changed (just the name of a script). Both the player and the bullet are on the same layer. Anyone could tell me what could have happened?

Destroy the clones by walking into them

I found a good re-spawner for my game and I respawn 50 spheres. I want them to disappear when I walk into them but they do nothing.
Here is my script:
using UnityEngine;
using System.Collections;
public class BoxDestroy : MonoBehaviour
{
void OntriggerEnter(Collider collider)
{
if (collider.gameObject.tag == "Player")
{
Destroy(gameObject);
}
}
}
Here is my re-spawner:
using UnityEngine;
using System.Collections;
public class spawner : MonoBehaviour
{
public GameObject objectToSpawn;
public int numberOfEnemies;
private float spawnRadius = 5;
private Vector3 spawnPosition;
// Use this for initialization
void Start ()
{
SpawnObject ();
}
void Update ()
{
}
void SpawnObject()
{
for (int i= 0; i < numberOfEnemies; i++)
{
spawnPosition = transform.position + Random.insideUnitSphere * spawnRadius;
Instantiate(objectToSpawn, spawnPosition, Quaternion.identity);
}
}
}
Any ideas?
OntriggerEnter should be OnTriggerEnter! Case sensitive :)
Did you actually tag your player-gameobject with a "player" tag?
Did you mark the colliders as triggers? OnTriggerEnter vs OnCollisionEnter
Do you have a rigidbody component on your player object?

Categories