delay between instantiating an object and void start() {} - c#

I am following a Unity tutorial (https://www.youtube.com/watch?v=BrlJsdP-VGo).
The problem I am having is whenever I instantiate the shot my player gameobject is firing, there is quite a long delay (about 1 sec) before it starts moving.
Here is my code:
Player gameobject:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Controller : MonoBehaviour
{
public GameObject bolt;
public float fireRate;
private Rigidbody rb;
private int speed = 10;
private float nextFire;
private void Awake()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
float mh = Input.GetAxis("Horizontal"), mv = Input.GetAxis("Vertical");
Vector3 move = new Vector3(mh, 0f, mv);
rb.velocity = move * speed;
rb.position = new Vector3(Mathf.Clamp(rb.position.x, -6, 6), 0f, Mathf.Clamp(rb.position.z, -4, 8));
rb.rotation = Quaternion.Euler(0, 0, rb.velocity.x * -5);
}
private void Update()
{
if (Input.GetKey("space") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(bolt, new Vector3(transform.position.x, 0,
transform.position.z + 1.25f), transform.rotation);
}
}
}
Shot that is being fired:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bolt_Mover : MonoBehaviour
{
Rigidbody rb;
public float speed;
private void Awake()
{
rb = GetComponent<Rigidbody>();
}
private void Start()
{
rb.velocity = transform.forward * speed;
}
}

Related

Why does OnCollisionEnter2D not working? Unity

I have an enemy prefab with and a bullet prefab with rigidbody2D and boxcolliders to both of them. I have made a TakeDamage function for the enemy when i made meelee combat and also a bullet shooting script. I made a simple OnCollisionEnter2D on the enemy(code is below) and they do collide and give the collision effect but the function doesn't work, it doesn't give any errors either... What do I do now?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemy : MonoBehaviour
{
public Transform player;
private Rigidbody2D rb;
[SerializeField] private SpriteRenderer sr;
private Vector2 movement;
public float moveSpeed = 5f;
public int maxHealth = 100;
int currentHealth;
Color32 colorRes = new Color32(255, 100, 50, 255);
public ParticleSystem deathParticles;
public GameObject projectile;
public int enemyDamage = 50;
public LayerMask rock;
// Start is called before the first frame update
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
sr = GetComponent<SpriteRenderer>();
currentHealth = maxHealth;
}
// Update is called once per frame
void Update()
{
sr.flipX = player.position.x - transform.position.x > 0;
Vector3 direction = player.position - transform.position;
direction.Normalize();
movement = direction;
}
private void FixedUpdate()
{
moveCharacter(movement);
}
void moveCharacter(Vector2 direction)
{
rb.MovePosition((Vector2)transform.position + (direction * moveSpeed));
}
public void TakeDamage()
{
currentHealth -= enemyDamage;
if(currentHealth <= 0)
{
Die();
}
StartCoroutine(BecomeRed());
}
void Die()
{
Instantiate(deathParticles, transform.position, Quaternion.identity);
Destroy(gameObject);
}
IEnumerator BecomeRed()
{
sr.color = colorRes;
yield return new WaitForSeconds(0.6f);
sr.color = Color.white;
}
void OnCollisionEnter2D(Collision2D coll)
{
Debug.Log("test");
if (coll.gameObject.name == "rock")
{
TakeDamage();
Destroy(projectile);
}
}
}

I need run add 1 to my var every 1 second in csharp without stopping the program

I want to add 1 to a variable meters when ever 1 seconds passed. Task.Delay wont work for some reason.
Here is all my code. Unfortunely im only a beginner at csharp so if you want make you can give me feedback on how to make it better.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
public int movementSpeed = 6;
private Rigidbody2D rb;
//the variable i want to add 1 to:
public int meters;
public double speeding = 5;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
Ymovement();
void Ymovement()
{
var movement = Input.GetAxis("Vertical");
transform.position += new Vector3(0, movement, 0) * Time.deltaTime * movementSpeed;
}
}
}
This is a pretty typical use case for InvokeRepeating:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
public int movementSpeed = 6;
private Rigidbody2D rb;
//the variable i want to add 1 to:
public int meters;
public double speeding = 5;
void Start()
{
rb = GetComponent<Rigidbody2D>();
InvokeRepeating("IncreaseMeters", 1f, 1f);
}
void Update()
{
Ymovement();
}
void Ymovement()
{
var movement = Input.GetAxis("Vertical");
transform.position += new Vector3(0, movement, 0) * Time.deltaTime * movementSpeed;
}
void IncreaseMeters()
{
meters += 1;
}
}

my player can fly for some reason, i have gravity on the rigidbody of the player

Im trying to make a 3d game with unity, but i dont know how to implement gravity, so i turned gravity for the rigidbody on. Also how could i implement jumping and wallrunning into this code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
float playerHeight = 2f;
public float moveSpeed = 6f;
float horizontalMovement;
float verticalMovement;
Vector3 moveDirection;
Rigidbody rb;
private void Start()
{
rb = GetComponent <Rigidbody>();
rb.freezeRotation = true;
}
bool isGrounded;
private void Update()
{
isGrounded = Physics.Raycast(transform.position, Vector3.down, playerHeight / 2 + 0.01f);
print (isGrounded);
MyInput();
}
void MyInput()
{
horizontalMovement = Input.GetAxisRaw("Horizontal");
verticalMovement = Input.GetAxisRaw("Vertical");
moveDirection = transform.forward * verticalMovement + transform.right * horizontalMovement;
}
private void FixedUpdate()
{
MovePlayer();
}
void MovePlayer()
{
rb.AddForce(moveDirection.normalized * moveSpeed, ForceMode.Acceleration);
}
}

I can't make my player move forward and backward! What is the problem?

I have been trying to create a video game but I stuck in this tutorial, in the tutorial it shows us to use input actions addon (What that does is it makes W-A-S-D or joystick type of keys easy to use) but even I watched the video after 3rd time I couldn't find the mistake! the problem is that I am not able to move my player forward or backward, I can only move it right and left. Please help I have tried so many things, like restarting the program or changing some code but it's not working can you help me to fix it?
Here is the first code to take the WASD commands from the addon script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputManager : MonoBehaviour
{
//Takes the wasd controls from addon
InputWASD playerControls;
public Vector2 movementInput;
public float verticalInput;
public float horizontalInput;
private void OnEnable()
{
if (playerControls == null)
{
playerControls = new InputWASD();
playerControls.PlayerMovement.Movement.performed += i => movementInput = i.ReadValue<Vector2>();
}
playerControls.Enable();
}
private void OnDisable()
{
playerControls.Disable();
}
public void HandleAllInputs()
{
HandleMovementInput();
//TODO: HandleJumpInput
// HandleAttackInput
// HandleDashInput
// HandleAbilityInput
}
private void HandleMovementInput()
{
verticalInput = movementInput.y;
horizontalInput = movementInput.x;
}
}
Here is the second code to use keys in movement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAct : MonoBehaviour
{
InputManager inputManager;
Vector3 moveDirection;
Transform cameraObject;
Rigidbody playersRB;
public float moveSpeed = 6f;
public float rotationSpeed = 15f;
private void Awake()
{
inputManager = GetComponent<InputManager>();
playersRB = GetComponent<Rigidbody>();
cameraObject = Camera.main.transform;
}
public void HandleAllAction()
{
HandleMovement();
HandleRotation();
}
private void HandleMovement()
{
moveDirection = cameraObject.forward * inputManager.verticalInput;
moveDirection = moveDirection + cameraObject.right * inputManager.horizontalInput;
moveDirection.Normalize();
moveDirection.y = 0;
moveDirection = moveDirection * moveSpeed;
Vector2 movementVelocity = moveDirection;
playersRB.velocity = movementVelocity;
}
private void HandleRotation()
{
Vector3 targetDirection = Vector3.zero;
targetDirection = cameraObject.forward * inputManager.verticalInput;
targetDirection = targetDirection + cameraObject.right * inputManager.horizontalInput;
targetDirection.Normalize();
targetDirection.y = 0;
if (targetDirection == Vector3.zero)
{
targetDirection = transform.forward;
}
Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
Quaternion playerRotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
transform.rotation = playerRotation;
}
}
Here is the third and last code to use first 2 codes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMain : MonoBehaviour
{
//Calling scripts
InputManager inputManager;
PlayerAct playerAct;
private void Awake()
{
inputManager = GetComponent<InputManager>();
playerAct = GetComponent<PlayerAct>();
}
private void Update()
{
inputManager.HandleAllInputs();
}
private void FixedUpdate()
{
playerAct.HandleAllAction();
}
}
I did what the man told me (in the tutorial) but mine is not working!
sometime maybe the video is so old and unity is keep updating so some code maybe is not work anymore , maybe you should use the getinput system like float x= Input.GetAxis("Horizontal")); and float z = Input.GetAxis("Vertical"); this two is use characterController and let see how it work

Unity: Player Death on object collision

I am extremely close to finishing my game, every code I posted works well but I want my player to die whether it collides with the box (which is the enemy). However, I've tried to do some research and I can't seem to find the solution. How do I do this? Here's the code for the Player (JugadorScript.cs):
using UnityEngine;
using System.Collections;
public class JugadorScript : MonoBehaviour
{
public float velocidad = -10f;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void moverIzquierda()
{
transform.Translate(Vector2.right * velocidad * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 0);
}
public void moverDerecha()
{
transform.Translate(Vector2.right * velocidad * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 180);
}
}
The EnemySpawner.cs code, which works excellent:
using UnityEngine;
using System.Collections;
using System;
public class EnemySpawner : MonoBehaviour
{
public GameObject BlockPrefab;
float maxSpawnRateInSeconds = 2.5f;
void Start()
{
Invoke("SpawnEnemy", maxSpawnRateInSeconds);
InvokeRepeating("IncreaseSpawnRate", 0f, 30f);
}
// Update is called once per frame
void Update()
{
}
void SpawnEnemy()
{
Vector2 min = Camera.main.ViewportToWorldPoint(new Vector2(0, 0));
Vector2 max = Camera.main.ViewportToWorldPoint(new Vector2(1, 1));
GameObject anEnemy = (GameObject)Instantiate(BlockPrefab);
anEnemy.transform.position = new Vector2(UnityEngine.Random.Range(min.x, max.x), max.y);
ScheduleNextEnemySpawn();
}
void ScheduleNextEnemySpawn()
{
float spawnInNSeconds;
if (maxSpawnRateInSeconds > 1f)
{
spawnInNSeconds = UnityEngine.Random.Range(1f, maxSpawnRateInSeconds);
}
else
spawnInNSeconds = 1f;
Invoke("SpawnEnemy", spawnInNSeconds);
}
void IncreaseSpawnRate()
{
if (maxSpawnRateInSeconds > 1f)
maxSpawnRateInSeconds--;
if (maxSpawnRateInSeconds == 1f)
CancelInvoke("IncreaseSpawnRate");
}
}
And the BlockScript.cs, which is my enemy script:
using UnityEngine;
using System.Collections;
public class BlockScript : MonoBehaviour
{
private GameObject wayPoint;
private Vector3 wayPointPos;
private Rigidbody2D rigidBody2D;
public bool inGround = true;
private float jumpForce = 400f;
private float speed = 6.0f;
void Start()
{
wayPoint = GameObject.Find("wayPoint");
}
private void awake()
{
rigidBody2D = GetComponent<Rigidbody2D>();
}
void Update()
{
if (inGround)
{
inGround = false;
rigidBody2D.AddForce(new Vector2(0f, jumpForce));
}
wayPointPos = new Vector3(wayPoint.transform.position.x, transform.position.y,
wayPoint.transform.position.z);
transform.position = Vector3.MoveTowards(transform.position,
wayPointPos, speed * Time.deltaTime);
Vector2 min = Camera.main.ViewportToWorldPoint(new Vector2(0, 0));
if (transform.position.y < min.y)
{
Destroy(gameObject);
}
}
}
As you can see in the doc, the function you are looking for is OnCollisionEnter.
Check this tutorial:
https://unity3d.com/es/learn/tutorials/topics/physics/detecting-collisions-oncollisionenter

Categories

Resources