This is the code. When I try to add the script to the sprite there's the "primary constructor body not allowed" error.
Inside the code editor there are no alerts.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class weapon : MonoBehaviour {
public GameObject dapo;
public float offset;
public Transform mira;
private float tiempo;
public float inicio;
private void Update()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
if (tiempo <= 0)
{
if (Input.GetMouseButtonDown(0))
{
Instantiate(dapo, mira.position, transform.rotation);
tiempo = inicio;
}
}
else
{
tiempo -= Time.deltaTime;
}
}
}
Related
I've been working on endless platform spawner but I don't know how to use decimal number in code. I've been trying to use private double or private decimal but I didn't figure it out. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatformManager : MonoBehaviour
{
[SerializeField]
private GameObject[] _platformPrefabs;
[SerializeField]
private int _zedOffset;
private int _yOffset;
// Start is called before the first frame update
void Start()
{
for (int i = 0; 1 < _platformPrefabs.Length; i++)
{
global::System.Object value = Instantiate(_platformPrefabs[i], new Vector3(0, i * -24.8, i * -30), Quaternion.Euler(0, 90, 0));
_zedOffset += -30;
_yOffset += -24.8;
}
}
public void RecyclePlatform(GameObject platform)
{
platform.transform.position = new Vector3(0, _yOffset, _zedOffset);
_zedOffset += -30;
_yOffset += -24.8;
}
}
You need to use floats
private float _myFloat;
_myFloat = 1.23f;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Left : MonoBehaviour
{
public float playerSpeed = 8;
void Update()
{
if (Input.GetKey(KeyCode.W))
{
transform.position = transform.position + new Vector3(0, playerSpeed * Time.deltaTime, 0);
}
if (Input.GetKey(KeyCode.S))
{
transform.position = transform.position + new Vector3(0, -playerSpeed * Time.deltaTime, 0);
}
}
}
How can i do it that the if statements only happen if the gameobject with this script is under y=7 and above y=-7?
I recently started working in Unity. I'm pretty new and have only been working with the software for a day, so I was creating a very basic movement script when an error popped up prompting me to close a curly bracket. I did so, but the error persisted. I think my code is fine, what's going on? I'm sure I'm probably just being an idiot.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Movement : MonoBehaviour {
[SerializeField] private int speed = 10;
[SerializeField] private int jump_height = 200;
[SerializeField] private float m_smoothing = 0.14;
private Vector3 m_Velocity = Vector3.zero;
Rigidbody2D m_Rigidbody;
public void Start()
{
m_Rigidbody = GetComponent<Rigidbody2D>();
}
public void Update()
{
[SerializeField] private float playerInputh = Input.GetAxisRaw("Horizontal");
Vector3 targetVelocity = new Vector2(playerInputh * speed, m_Rigidbody.velocity.y);
m_Rigidbody.velocity = Vector3.SmoothDamp(m_Rigidbody.velocity, targetVelocity, ref m_Velocity, m_smoothing);
if (Input.GetKeyDown("space"))
{
m_Rigidbody.AddForce(new Vector2(0f, jump_height));
}
}
}
The variable "m smoothing" is of type float, and numbers of type float must be accompanied with an f after the end.
For example 5 is of type int or float, 5.0 is of type float and should be written 5.0f, and 0.14 is of type float and should be written 0.14f.
The other problem is that you have entered [SerializeField] private in a method. To declare a local variable, that is, it can be called up only in that method, just write the type and name, and if you want, then assign it a value.
Learn more, because I have simplified some things, but I hope I have been clear.
Here is your error-free code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Movement : MonoBehaviour
{
[SerializeField] private int speed = 10;
[SerializeField] private int jump_height = 200;
[SerializeField] private float m_smoothing = 0.14f;
private Vector3 m_Velocity = Vector3.zero;
Rigidbody2D m_Rigidbody;
public void Start()
{
m_Rigidbody = GetComponent<Rigidbody2D>();
}
public void Update()
{
float playerInputh = Input.GetAxisRaw("Horizontal");
Vector3 targetVelocity = new Vector2(playerInputh * speed, m_Rigidbody.velocity.y);
m_Rigidbody.velocity = Vector3.SmoothDamp(m_Rigidbody.velocity, targetVelocity, ref m_Velocity, m_smoothing);
if (Input.GetKeyDown("space"))
{
m_Rigidbody.AddForce(new Vector2(0f, jump_height));
}
}
}
if you think my answer helped you, you can mark it as accepted. I would very much appreciate it :)
I am tring to follow this tutorial https://www.youtube.com/watch?v=gmaAK_BXC4c to make a vr gun but I am getting an the following error:
'XRBaseInteractable' does not contain a definition for 'onSelectEntering' and no accessible extension method 'onSelectEntering' accepting a first argument of type 'XRBaseInteractable' could be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]csharp(CS1061)
for the following lines :
socketInteractor.onSelectEntering.AddListener(AddMagazine);
socketInteractor.onSelectExiting.AddListener(RemoveMagazine);
Here is my code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;
[AddComponentMenu("Nokobot/Modern Guns/Simple Shoot")]
public class SimpleShoot : MonoBehaviour
{
[Header("Prefab Refrences")]
public GameObject bulletPrefab;
public GameObject casingPrefab;
public GameObject muzzleFlashPrefab;
[Header("Location Refrences")]
[SerializeField] private Animator gunAnimator;
[SerializeField] private Transform barrelLocation;
[SerializeField] private Transform casingExitLocation;
[Header("Settings")]
[Tooltip("Specify time to destory the casing object")] [SerializeField] private float destroyTimer = 2f;
[Tooltip("Bullet Speed")] [SerializeField] private float shotPower = 500f;
[Tooltip("Casing Ejection Speed")] [SerializeField] private float ejectPower = 150f;
public AudioSource source;
public AudioClip fireSound;
public AudioClip reload;
public Magazine magazine;
public AudioClip noAmmo;
public XRBaseInteractable socketInteractor;
public void AddMagazine(XRBaseInteractable interactable)
{
magazine = interactable.GetComponent<Magazine>();
source.PlayOneShot(reload);
}
public void RemoveMagazine(XRBaseInteractable interactable)
{
magazine = null;
}
public void Slide()
{
}
void Start()
{
if (barrelLocation == null)
barrelLocation = transform;
if (gunAnimator == null)
gunAnimator = GetComponentInChildren<Animator>();
socketInteractor.onSelectEntering.AddListener(AddMagazine);
socketInteractor.onSelectExiting.AddListener(RemoveMagazine);
}
public void PullTheTrigger()
{
if(magazine && magazine.numberOfBullet > 0)
{
gunAnimator.SetTrigger("Fire");
}
else
{
source.PlayOneShot(noAmmo);
}
}
//This function creates the bullet behavior
void Shoot()
{
magazine.numberOfBullet--;
source.PlayOneShot(fireSound);
if (muzzleFlashPrefab)
{
//Create the muzzle flash
GameObject tempFlash;
tempFlash = Instantiate(muzzleFlashPrefab, barrelLocation.position, barrelLocation.rotation);
//Destroy the muzzle flash effect
Destroy(tempFlash, destroyTimer);
}
//cancels if there's no bullet prefeb
if (!bulletPrefab)
{ return; }
// Create a bullet and add force on it in direction of the barrel
Instantiate(bulletPrefab, barrelLocation.position, barrelLocation.rotation).GetComponent<Rigidbody>().AddForce(barrelLocation.forward * shotPower);
}
//This function creates a casing at the ejection slot
void CasingRelease()
{
//Cancels function if ejection slot hasn't been set or there's no casing
if (!casingExitLocation || !casingPrefab)
{ return; }
//Create the casing
GameObject tempCasing;
tempCasing = Instantiate(casingPrefab, casingExitLocation.position, casingExitLocation.rotation) as GameObject;
//Add force on casing to push it out
tempCasing.GetComponent<Rigidbody>().AddExplosionForce(Random.Range(ejectPower * 0.7f, ejectPower), (casingExitLocation.position - casingExitLocation.right * 0.3f - casingExitLocation.up * 0.6f), 1f);
//Add torque to make casing spin in random direction
tempCasing.GetComponent<Rigidbody>().AddTorque(new Vector3(0, Random.Range(100f, 500f), Random.Range(100f, 1000f)), ForceMode.Impulse);
//Destroy casing after X seconds
Destroy(tempCasing, destroyTimer);
}
}
I'm making a 3d isometric game and I'm trying to shoot things from player to a direction taked with a joystick and I would like that it shoots when I release the joystick. You can easly search Brawl Stars video to understand better what I mean. The first script is of the joystick and the second for the shoot(I putted it inside the player). It now gives me this error: the object you want to instantiate is null.
Joystick's script :
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class rightjoystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
private Image bgImg;
private Image joystickImg;
private Vector3 inputVector;
private void Start()
{
bgImg = GetComponent<Image>();
joystickImg = transform.GetChild(0).GetComponent<Image>();
}
public virtual void OnDrag(PointerEventData ped)
{
Vector2 pos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(bgImg.rectTransform, ped.position, ped.pressEventCamera, out pos))
{
pos.x = (pos.x / bgImg.rectTransform.sizeDelta.x);
pos.y = (pos.y / bgImg.rectTransform.sizeDelta.y);
inputVector = new Vector3(pos.x * 2, 0, pos.y * 2);
inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;
// Move joystickImg
joystickImg.rectTransform.anchoredPosition =
new Vector3(inputVector.x * bgImg.rectTransform.sizeDelta.x / 3
, inputVector.z * (bgImg.rectTransform.sizeDelta.y / 3));
}
}
public virtual void OnPointerDown(PointerEventData ped)
{
OnDrag(ped);
}
public virtual void OnPointerUp(PointerEventData ped)
{
inputVector = Vector3.zero;
joystickImg.rectTransform.anchoredPosition = Vector3.zero;
}
public float Horizontal()
{
if (inputVector.x != 0)
return inputVector.x;
else
return Input.GetAxis("Horizontal");
}
public float Vertical()
{
if (inputVector.z != 0)
return inputVector.z;
else
return Input.GetAxis("Vertical");
}
}
shooting script :
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shoot : MonoBehaviour
{
public Rigidbody proiettile;
public float launchForce = 70f;
public rightjoystick moveJoystick;
private Vector3 dir = Vector3.zero;
public void Update()
{
dir.x = moveJoystick.Horizontal();
dir.z = moveJoystick.Vertical();
}
private void FixedUpdate()
{
var projectileInstance = Instantiate(proiettile);
projectileInstance.AddForce(dir * launchForce);
}
}
I solved with this:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class shoot : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
private Image bgImg;
private Image joystickImg;
private Vector3 inputVector;
public Rigidbody proiettile;
private Vector3 dir = Vector3.zero;
private Vector3 newpos;
public float launchForce;
public Rigidbody Player;
private Rigidbody clone;
private void Start()
{
bgImg = GetComponent<Image>();
joystickImg = transform.GetChild(0).GetComponent<Image>();
}
public virtual void OnDrag(PointerEventData ped)
{
Vector2 pos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(bgImg.rectTransform, ped.position, ped.pressEventCamera, out pos))
{
pos.x = (pos.x / bgImg.rectTransform.sizeDelta.x);
pos.y = (pos.y / bgImg.rectTransform.sizeDelta.y);
inputVector = new Vector3(pos.x * 2 +1, 0, pos.y * 2 - 1);
inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;
// Move joystickImg
joystickImg.rectTransform.anchoredPosition =
new Vector3(inputVector.x * bgImg.rectTransform.sizeDelta.x / 3
, inputVector.z * (bgImg.rectTransform.sizeDelta.y / 3));
}
}
public virtual void OnPointerDown(PointerEventData ped)
{
OnDrag(ped);
}
public virtual void OnPointerUp(PointerEventData ped)
{
dir.x = Horizontal();
dir.z = Vertical();
newpos = dir * (launchForce);
clone = Instantiate(proiettile, Player.transform.position, Player.transform.rotation);
clone.transform.position=Vector3.MoveTowards(Player.transform.position,newpos,10f);
// joystick come back to start position
inputVector = Vector3.zero;
joystickImg.rectTransform.anchoredPosition = Vector3.zero;
clone.timeoutDestructor = 5;
}
public float Horizontal()
{
if (inputVector.x != 0)
return inputVector.x;
else
return Input.GetAxis("Horizontal");
}
public float Vertical()
{
if (inputVector.z != 0)
return inputVector.z;
else
return Input.GetAxis("Vertical");
}
}