- Home /
Can't Instantiate the GameObject and make it parent to GameObject which it hits.
I wanna Instantiate the Gameobject(c4_bomb) when player press keycode I. I'm using Raycast to check that if player is at 1m from the wall. Then I wanna instantiate the GameObject and make the GameObject (c4_bomb) children of the wall.
here is the code:
using UnityEngine;
using System.Collections;
/// <summary>
/// Class responsible for managing the items
/// </summary>
public class Items : MonoBehaviour
{
[Header("Grenades")]
public GameObject grenade; // The grenade prefab.
public Transform throwPos; // Position where grenade will be instantiated.
public float throwForce = 10; // How far the player can throw the grenade.
public bool infiniteGrenades;
public int numberOfGrenades = 3;
public int maxNumberOfGrenades = 3;
public float maxForceMultiplier = 3; // The maximum force multiplier.
private float forceMultiplier = 0; // Throw force multiplier.
public int numberofBombs;
public float delayToThrow = 0.3f; // Delay until instantiate the grenade.
[Header("Animations")]
public Animation grenadeAnim;
public GameObject C4_bomb;
bool isThrown;
public Camera mainCamera;
[Space()]
public string pullAnimName = "";
public string throwAnimName = "";
public AudioClip pullSound;
public AudioClip throwSound;
public float pullVolume = 0.3f;
public float throwVolume = 0.3f;
private bool canThrowBomb;
[Space()]
public WeaponsManager weaponManager;
public AudioManager audioManager;
public PlayerUI ui;
private void Update ()
{
GetUserInput(); // Checks if the user is pressing some action key.
UpdateUI(); // Update the UI showing the amount of grenades.
}
/// <summary>
/// Checks whether the user is pressing any action key and invokes the corresponding method.
.
/// </summary>
private void GetUserInput ()
{
if (numberofBombs > 0) // Still have grenades available?
{
if (!isThrown) // Is not already throwing a grenade?
{
if (Input.GetKeyDown(KeyCode.I) && weaponManager.canUseItems)
{
HoldToThrowBomb(); // Pull the grenade pin.
canThrowBomb = true; // Can throw the grenade.
}
}
else
{
// Hold the Key to throw the grenade with more force.
if (Input.GetKey(KeyCode.I))
{
if (forceMultiplier <= maxForceMultiplier)
forceMultiplier += Time.deltaTime; // Increase the force multiplier with time.
}
// Release the Key to throw the grenade with the current force (forceMultiplier).
if (Input.GetKeyUp(KeyCode.I) && canThrowBomb)
{
canThrowBomb = false;
StartCoroutine(ThrowBomb(forceMultiplier));
forceMultiplier = 0;
}
}
}
}
private void HoldToThrowBomb(){
isThrown = true;
weaponManager.HideCurrentWeapon ();
}
private IEnumerator ThrowBomb(float holdTime){
if (GetPullAnimTime() < holdTime) // If has finished the pull the pin animation.
{
//ThrowAnimation(); // Play throw animation.
yield return new WaitForSeconds(delayToThrow);
InstantiateBomb(holdTime);
yield return new WaitForSeconds(GeThrowAnimTime() - delayToThrow);
weaponManager.SelectCurrentWeapon(); // Activate the current weapon after throwing the grenade.
isThrown = false;
}
else // Wait until finish the pull animation to play throw animation.
{
yield return new WaitForSeconds(GetPullAnimTime() - holdTime);
//ThrowAnimation(); // Play throw animation.
yield return new WaitForSeconds(delayToThrow);
InstantiateBomb(holdTime);
yield return new WaitForSeconds(GeThrowAnimTime() - delayToThrow);
weaponManager.SelectCurrentWeapon(); // Activate the current weapon after throwing the
isThrown = false;
}
}
private void InstantiateBomb (float holdTime)
{
Vector3 direction = mainCamera.transform.TransformDirection(Vector3.forward); // Bullet direction.
Vector3 origin = mainCamera.transform.position; // Bullet origin.
Ray ray = new Ray (origin, direction); // Creates a ray starting at origin along direction.
RaycastHit hitInfo; // Structure used to get information back from a raycast.
if (Physics.Raycast (ray, out hitInfo, 1f)) { // Checks whether the ray intersects something.
Vector3 contact = hitInfo.point;
Quaternion rot = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
GameObject bombClone = Instantiate (C4_bomb, contact, rot) as GameObject;
bombClone.transform.localPosition += .02f * hitInfo.normal;
bombClone.transform.parent = hitInfo.transform;
//grenadeClone.GetComponent<GrenadeScript>().Detonate(holdTime);
//C4_bomb.GetComponent<GrenadeScript> ().Detonate (); // Calls the method responsible for blowing up the grenade.
// Adds force to the grenade to throw it forward.
C4_bomb.GetComponent<Rigidbody> ().velocity = bombClone.transform.TransformDirection (Vector3.forward)
* throwForce * (holdTime > 1 ? holdTime : 1);
}
}
/// <summary>
/// Method responsible for play the Pull animation.
/// </summary>
private void PullAnimation ()
{
grenadeAnim.Play(pullAnimName);
audioManager.PlayGenericSound(pullSound, pullVolume);
}
/// <summary>
/// Method responsible for play the Throw animation.
/// </summary>
private void ThrowAnimation()
{
grenadeAnim.Play(throwAnimName);
audioManager.PlayGenericSound(throwSound, throwVolume);
}
/// <summary>
/// Returns the duration of the Throw animation in seconds.
/// </summary>
private float GeThrowAnimTime()
{
return grenadeAnim != null ? throwAnimName.Length > 0 ? grenadeAnim[throwAnimName].length : 0 : 0;
}
/// <summary>
/// Returns the duration of the Pull animation in seconds.
/// </summary>
private float GetPullAnimTime ()
{
return grenadeAnim != null ? pullAnimName.Length > 0 ? grenadeAnim[pullAnimName].length : 0 : 0;
}
}
$$anonymous$$ake some small steps to find a solution. First of all check if raycast is working. Change max distance to 100f and add a debug.log into it to see the result. Then, if its working, you can find the actual distance with Vector3.Distance and if its
Your answer
Follow this Question
Related Questions
Having trouble making headshots do more damage (JS) 1 Answer
Null Reference Exception issue getting the tag of an object hit by Raycast 2 Answers
How to Instantiate a line or a ray that goes through all colliders and send a message to them???? 1 Answer
Player Attacking Enemy Issue 0 Answers
Trouble with rigidbody.AddForce 0 Answers