• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by shadowpuppet · Jan 09, 2017 at 11:37 PM · raycasthitinstantiate prefab

instantiating prefab at object center not at hit point

simple script below I want to put on various objects and instantiate bullet hits according to the material/texture on that object. It works in that the test object knows it's being hit and IS instantiating the prefab but it is doing so at the objects center rather than where I shot it. I tried altering the gun script to add the variables there but...I got the script in the store and got as far as making a bullet hole spawn as a blood splat instead when I hit things tagged "enemy". but I can't seem to add more variables without breaking the script. So hoping I could put the script on the objects I shoot at. I can tell by the simple code that instantiating at the objects center would be the result, but this is my only attempt that even got THAT much to happen. Been searching all day and trying various "solutions" but they all seem to be tailored to the posters specific needs which aren't the same

 using UnityEngine;
 using System.Collections;
 
 public class hitByRay : MonoBehaviour {
     public GameObject prefab;
     void Start(){
 
     }
     void HitByRay () {
         Debug.Log ("yippee! you shot me");
 
         Instantiate(prefab, transform.position , transform.rotation);
     }
 }
 


Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by Scoutas · Jan 10, 2017 at 02:47 AM

First of all Instantiate(prefab, transform.position , transform.rotation); instantiates the object at the center of the object that the script is attached to, because transform.position is the position of the transform of the object.

Anyway, thing is the solution I'd offer is, inside of your weapon script (where you are doing Physics.Raycast is presume), have a Vector3 that would hold the direction of the Ray and that's mostly it.

Now, Physics.Raycast has an option to return a struct called RaycastHit, where it stores some information about the object that it hit and where it hit it.

 Vector3 raycastDirection;
 RaycastHit hitInfo;
 (Physics.Raycast(Vector3 origin, raycastDirection, out hitInfo, maxDistance, layerMask)){
     // At this point, if the Raycast hit something that you wanted it to hit, it would have already sent out the information to the hitInfo struct.
     // That struct holds several great things
     // The point that the ray hit the other object: hitInfo.point
     // Knowing this information, you can instantiate the "bulletHole" prefab at that point and parent it to the object that it hit.
     GameObject bulletHole = (GameObject)Instantiate(bulletHolePrefab, hitInfo.point, Quaternion.identity);
     bulletHole.transform.SetParent(hitInfo.transform);
 }

At this point, you might want to tweak the rotation of it a bit, but generally, what that script would do: If you hit an enemy, instantiate a bulletHole prefab at that position that the raycast hit and parent it to that object.

If it's not clear, I can elaborate on all this.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by shadowpuppet · Jan 10, 2017 at 07:14 PM

I know that the code SHOULD be in the weapon script because that is where the code is where can already instantiate bullet holes or bloodplatter if I hit people. The problem is that I can not add anything else to my weapon script without breaking it it seems. As stated originally , I bought the scripts in the store. It came with a weaponEditor script as well as the weapon script, and I copied the weapon script to make another weaponAim script ( for when looking down the sights) THIS script is where I was able to insert my bloodsplat. but NOT in the weapon script or weaponEditor script. In otherwords...it's way over my head. Not even sure how I got the bloodsplatter to work and why I CAN"T get it to work in the Weapon script - weaponAIm and weapon script are IDENTICAL all I do is tweak the variables in the inspector to effect bullet accuracy but in the inspector view the scripts variable fields aren't the sameBut, here is the weaponAim script if you can see where to SUCCESSFULLY add more instantaitions let me know please

 using UnityEngine;
 using System.Collections;
 
 public class WeaponAim : MonoBehaviour {
 
 
     public Transform muzzlePoint;
     public GameObject bulletHolePrefab, muzzleFlashPrefab;
     public AudioClip fireSound;
     public bool shouldWeaponFire, semiAutoFire;
     public float spread = 0.05f;
     public float minSpread = 0.01f;
     public float maxSpread = 0.5f;
     public float maxBulletDist = 100.0f;
     public float fireDelay = 0.15f;
     public float bulletForce = 2000.0f;
     public GameObject bloodsplatPreFab;
 
     private float fireTimer;
     
 
     void Start () {
         Initialize ();
     
     }
     
     void Initialize () {
         NullErrorCheck ();
     }
     
 
     void NullErrorCheck () {
         if (!muzzlePoint) {
             Debug.LogError("Please make sure to set the muzzle point for your weapon!");
             Debug.Break ();
         }
         if (!bulletHolePrefab) {
             Debug.LogError("Please make sure to set the bullet hole prefab for your weapon!");
             Debug.Break ();
         }
         if (!muzzleFlashPrefab) {
             Debug.LogError("Please make sure to set the muzzle flash prefab for your weapon!");
             Debug.Break ();
         }
         if (!fireSound) {
             Debug.LogError("Please make sure to set the fire soound for your weapon!");
             Debug.Break ();
         }
         if (!shouldWeaponFire) {
             Debug.LogWarning("Your weapon will not be able to fire, make sure this is what you want!");
         }
     }
     
 
     void LateUpdate () {
         if (!muzzlePoint)
             return;
         
     
         if(Input.GetKeyDown(KeyCode.X)) {
             semiAutoFire = !semiAutoFire;
         }
         
         /* Checks to make sure you can fire the weapon and that the game
          * is not paused */
         if(shouldWeaponFire && Time.timeScale > 0.0f)
             WeaponFire ();
         
     }
     
     /* This is what controls the different fire modes for semi, or
      * automatic */
     void WeaponFire() {
         if(semiAutoFire && Input.GetMouseButtonDown(0)) {
             Fire();
         } else
         if(!semiAutoFire && Input.GetMouseButton(0)) {
             Fire();
         }
     }
     
     /* This is where we fire our weapon and play our muzzleflash, bullet
      * effects, and sound */
     void Fire() {
         if (!bulletHolePrefab || !muzzleFlashPrefab || !fireSound)
             return;
         
         /* Controls the rate of fire */
         if(Time.time >= fireTimer) {
             audio.PlayOneShot(fireSound);
             
             GameObject mf = Instantiate(muzzleFlashPrefab, muzzlePoint.position, muzzlePoint.rotation) as GameObject;
             mf.transform.parent = muzzlePoint;
             
             /* Calls our function to spawn the bullet */
             SpawnBullethole();
             
             fireTimer = Time.time + fireDelay;
         }
     }
     
     /* This is where we spawn our bullet hole, give our cast
      * weapon spread, and add force to any hit rigidbodies */
     void SpawnBullethole() {
         RaycastHit hit;
         Vector3 fwd = muzzlePoint.TransformDirection(Vector3.forward);
     //    Debug.DrawRay (transform.position, fwd, Color.green);
         if(Physics.Raycast(muzzlePoint.position, fwd, out hit, maxBulletDist)) {
             
             Vector3 tmpLoc = muzzlePoint.position;
             hit.transform.SendMessage ("HitByRay");
             Debug.DrawRay (transform.position, fwd, Color.green);
 
         
             if(Physics.Raycast(tmpLoc, fwd, out hit)) {
                 GameObject bs = Instantiate(bulletHolePrefab, hit.point + (hit.normal * 0.01f), Quaternion.LookRotation(hit.normal)) as GameObject;
                 bs.transform.parent = hit.transform;
 
                 if(hit.rigidbody && !hit.rigidbody.isKinematic) {
                     hit.rigidbody.AddForce(muzzlePoint.forward * bulletForce);
 
             if(hit.transform.gameObject.tag == ("enemy"))
                     if(Physics.Raycast(tmpLoc, fwd, out hit)) {
                         GameObject bh = Instantiate(bloodsplatPreFab, hit.point + (hit.normal * 0.01f), Quaternion.LookRotation(hit.normal)) as GameObject;
                         bh.transform.parent = hit.transform;
 
                         if(hit.transform.gameObject.tag == ("wall"))
                         if(Physics.Raycast(tmpLoc, fwd, out hit)) {
                             GameObject br = Instantiate(bulletHolePrefab, hit.point + (hit.normal * 0.01f), Quaternion.LookRotation(hit.normal)) as GameObject;
                             br.transform.parent = hit.transform;
 
 
 
                 
             float spreadMod = hit.distance * spread;
             
             spreadMod = Mathf.Clamp(spreadMod, minSpread, maxSpread);
             
             tmpLoc.x += Random.Range(-spreadMod, spreadMod);
             tmpLoc.y += Random.Range(-spreadMod, spreadMod);
             tmpLoc.z += Random.Range(-spreadMod, spreadMod);
             
             
                 
 
                 }
             }
         }
     }
 }
 }
 }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Scoutas · Jan 11, 2017 at 02:06 AM 0
Share

I'd suggest having just one script, especially if they are identical and you just change some variables around. It'd be better to create another script, that based on your inputs would change the variables inside a singular weapon script that is attached to your gun. It might just be where the problem originates from, but you'd have to do a little debugging with that.

And while I don't see too many problems with the code, it should work, the SpawnBulletHole method could be simplified immesnly as it's nested and half of the things there are redundant and need refactoring.

 void SpawnBullethole() {
 
         RaycastHit hit;
         Vector3 fwd = muzzlePoint.TransformDirection(Vector3.forward);
         if(Physics.Raycast(muzzlePoint.position, fwd, out hit, maxBulletDist)) {
 
             // Okay, so at this point, there was an awful lot of uneccessary code. 
             // I cleared most of it up, did remove the random spread thing as well. (Implement it here if you want.)
 
             // Let's declare a variable, which will decide, what kind of thing we need to instantiate.
             GameObject instantiatingPrefab = null;
 
 
             // Now we choose it.
             if (hit.transform.tag == "enemy") {
                 instantiatingPrefab = bloodsplatPreFab;
             } else if (hit.transform.tag == "wall") {
                 instantiatingPrefab = bulletHolePrefab;
             }
 
             // Now, let's instantiate the bullet hole or blood splat.
             GameObject bulletHole = (GameObject) Instantiate(instantiatingPrefab, hit.point + (hit.normal * 0.01f), Quaternion.LookRotation(hit.normal));
             bulletHole.transform.parent = hit.transform;
 
             // You want to check if the object is kinematic or not and add force if it is not.
             if(hit.rigidbody && hit.rigidbody.is$$anonymous$$inematic == false){
                 hit.rigidbody.AddForce (muzzlePoint.forward * bulletForce);
             }
         }
     }

This should be about it, really. As for the changing variables:

     public void ChangeVariables(float _$$anonymous$$Spread, float _maxSpread){
         // $$anonymous$$ake a reference to this script in another script (e.g. mouseControl)
         // there, once you press right mouse button (to zoom, for example) change the state
         // of zoomedIn to true and then execute a method, which would check if
         // zoomedIn is true or not, and use the ChangeVariables() method accordingly
         // and send it required variables. 
 
         // For example, I'd be sending in new max and $$anonymous$$ spread variables.
         // Assign the variables that you sent into this script.
 
         $$anonymous$$Spread = _$$anonymous$$Spread;
         maxSpread = _maxSpread;
 
         // The '_' or the underscore is there, so you would be able to differentiate between the variables the script holds
         // and the variables you sent in.
     }

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

87 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to instantiate objects to mesh while restricting the spawn area on a single axis? 2 Answers

RayCastHit Not Returning Rigidbody 0 Answers

Advanced AI sight? AI can detect you if part of you is visible to them. Is it Possible? 1 Answer

How to cast a Ray using local pivot of an object? 1 Answer

Physics Raycast not working 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges