- Home /
How do i enter a script from another scriptP (C#)
In my game I want to have a car to move when the player is close enough to the car. so I want to check the player position witch I have done. then I have to enter that value from my car to activate the animation (the animation part do I already have)
hope there is some wonderful people that can help me! :-)
Answer by clunk47 · Jul 26, 2013 at 02:32 PM
Click here to be redirected to the Unity Script Reference for GetComponent
With little to go on here, like what scripts you are using and what objects those scripts are on, I'll show you a basic example of how to access a script that is attached to another object.
//Example.cs
//This would be an example of a script attached to your player, accessing a script on an object with Tag "Car".
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
GameObject car;
void Awake()
{
car = GameObject.FindGameObjectWithTag("Car");
if(car != null)
{
if(car.GetComponent<Animation>())
car.GetComponent<Animation>().Play();
else
print ("No animation attached to "+car.name);
}
}
}
Get your distance like so:
GameObject car;
float distance;
distance = Vector3.Distance(car.transform.position, transform.position);
if(distance <= 14)
car.animation.Play();
I can see that you are a lot better than I am!!! I have been scripting ½ year. do you think something like this would work too??
public GameObject Car;
if(Car.transform.position.y >= 14) { animation.Play(aimation) }
sounds like you want something like:
if(Vector3.Distance(Car.transform.position, Player.transform.position) <= 14) Car.animation.Play();
There is also a video tutoral on GetComponent in the Beginner Scripting Unity Learn $$anonymous$$odule.
@phil2988 that just means the car's position on the y axis would need to move up before the animation plays. If you want to check the distance between your player and your car you would do something like this:
GameObject car;
float distance;
distance = Vector3.Distance(car.transform.position, transform.position);
if(distance <= 14)
car.animation.Play();
This is just a quick example, you'd need to use your own methods of course.
what I want is to check when my player is at 14 on the y axe and then play the animation
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Unity jumping sound, help. 1 Answer
function Start () problem!! 3 Answers
Help with Basic Movement Script 1 Answer
What am I doing wrong in this 1 Answer