- Home /
Question by
dollarino · Jun 27, 2020 at 01:50 PM ·
unity 5scripting problemaudioclipreference-other-objectholding
How to make audioclip reference to another script
I have this code, it destroys specific object with tag on hold(2sec). I took code from here: https://www.youtube.com/watch?v=jjBeh2xLckA
Following tutorial, he created "Item" script and attached to an object. var hitItem = hitInfo.collider.GetComponent< Item>();
So how can I add sound to "Item" when it is picked/destroyed. I dont know how to make reference to another script
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class HoldToPickup : MonoBehaviour {
[SerializeField]
[Tooltip("Probably just the main camera.. but referenced here to avoid Camera.main calls")]
private Camera camera;
[SerializeField]
[Tooltip("The layers the items to pickup will be on")]
private LayerMask layerMask;
[SerializeField]
[Tooltip("How long it takes to pick up an item.")]
private float pickupTime = 2f;
[SerializeField]
[Tooltip("The root of the images (progress image should be a child of this too)")]
private RectTransform pickupImageRoot;
[SerializeField]
[Tooltip("The ring around the button that fills")]
private Image pickupProgressImage;
[SerializeField]
private TextMeshProUGUI itemNameText;
private Item itemBeingPickedUp;
private float currentPickupTimerElapsed;
private void Update()
{
SelectItemBeingPickedUpFromRay();
if (HasItemTargetted())
{
pickupImageRoot.gameObject.SetActive(true);
if (Input.GetKey(KeyCode.R))
{
IncrementPickupProgressAndTryComplete();
}
else
{
currentPickupTimerElapsed = 0f;
}
UpdatePickupProgressImage();
}
else
{
pickupImageRoot.gameObject.SetActive(false);
currentPickupTimerElapsed = 0f;
}
}
private bool HasItemTargetted()
{
return itemBeingPickedUp != null;
}
private void IncrementPickupProgressAndTryComplete()
{
currentPickupTimerElapsed += Time.deltaTime;
if (currentPickupTimerElapsed >= pickupTime)
{
MoveItemToInventory();
}
}
private void UpdatePickupProgressImage()
{
float pct = currentPickupTimerElapsed / pickupTime;
pickupProgressImage.fillAmount = pct;
}
private void SelectItemBeingPickedUpFromRay()
{
Ray ray = camera.ViewportPointToRay(Vector3.one / 2f);
Debug.DrawRay(ray.origin, ray.direction * 2f, Color.red);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo, 2f, layerMask))
{
var hitItem = hitInfo.collider.GetComponent<Item>();
if (hitItem == null)
{
itemBeingPickedUp = null;
}
else if (hitItem != null && hitItem != itemBeingPickedUp)
{
itemBeingPickedUp = hitItem;
itemNameText.text = "Eat " + itemBeingPickedUp.gameObject.name;
}
}
else
{
itemBeingPickedUp = null;
}
}
public void MoveItemToInventory()
{
Destroy(itemBeingPickedUp.gameObject);
itemBeingPickedUp = null;
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613001927im_/https://answers.unity.com/themes/thub/images/avi.jpg)