Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • 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 /
avatar image
1
Question by cernst77 · Aug 15, 2011 at 09:19 PM · c#buttongetcomponentelevator

Cache GetComponent correctly in C#

Here is my problem. Button on wall has button script. Elevator platform has Elevator script (everything is C#) When Button is pushed it needs to call GoToFloor in the Elevator script.

I cobbled together this from other examples on Unity Answers.

How do I make the result of GetComponent Public so every function in Button.cs can use it? Currently it is resisting my attempts to use GetComponent in one place and save it for use somewhere else without calling GetComponent AGAIN (which I have read you only want to do once for efficiency sake:

CODE:

Elevator.cs using UnityEngine; using System.Collections; using UnityEngine; using System.Collections;

public class Elevator : MonoBehaviour {

 public Transform target;
 private float initialx = 159 ;
 private float initialy = 0.2F ;
 private float initialz = 821.4F;
 private float floor1Height = 0F;
 private float floor2Height = 10F;
 private int floorNum;
 private float elevatorSpeed ;
 private Vector3 velocity = Vector3.zero;
 private float smoothTime = 0.3F;
 private float floor3Height ;
 private GameObject elevator;
 private bool elevatorActive = false;
 private float elevatorDestination ;

 void Start()
 {
     // initialise variables which must have a value, otherwise errors ensue
     elevator = this.gameObject;
     elevatorActive = false;
     elevatorDestination = elevator.transform.position.y;
 
 }

 void Update() {
     if(elevatorActive)
     {
         MoveElevator();
     }
 }

 void MoveElevator()
 {
     // Move the elevator

     Vector3 targetPosition = target.TransformPoint(new Vector3(initialx,initialy + elevatorDestination,initialz));
     transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
            
     
     //elevator.transform.position.y = Mathf.Lerp(elevator.transform.position.y, elevatorDestination, elevatorSpeed * Time.deltaTime);

     // Disable the elevator if it is within a very small margin of the destination, ie it is 'close enough' so stop
     //if(Mathf.Abs(elevator.transform.position.y - elevatorDestination) < 0.01)
     //{
     //    print("stopped elevator");
     //    elevatorActive = false;
     //}
 }

 public void GoToFloor(int floorNum)
 {
     switch(floorNum)
     {
         case 1:
             elevatorDestination = floor1Height;
             break;
         case 2:
             elevatorDestination = floor2Height;
             break;
         case 3:
             elevatorDestination = floor3Height;
             break;
         default:
             elevatorDestination = floor1Height;
             break;
     }

     elevatorActive = true;
 }

 void StopElevator()
 {
     elevatorActive = false;
 }

 void ResumeElevator()
 {
     elevatorActive = true;
 }

}

BUTTON CODE:

 using UnityEngine;

using System.Collections;

public class Button : MonoBehaviour { public GameObject target; public bool pushed = false; //public myelevator; (does not work)

 void Start() {
     //GameObject myelevator = GameObject.Find("elevator");
      Elevator myelevator = GetComponent<Elevator>();  // How do I export myelevator so it can be used in OnMouseUp()?
     // Doing a GetComponent once is the best idea I understand, but how do I save it for other functions?
     
     //myelevator bar = myelevator.GetComponent<GoToFloor()>();
     
 }

 void OnMouseEnter() {
     //renderer.material.SetColor("_OutlineColor", Color.blue); .//not important right now
 }

 void OnMouseExit() {
     //renderer.material.SetColor("_OutlineColor", Color.black); //not important right now
 }

 void OnMouseUp() {
     pushed = true;
     //Elevator.elevator.GoToFloor(2);

     myelevator.GoToFloor(2); // myelevator from above not recognized! why?
     Debug.Log("Button Pushed.");
 }

   
 void Done() {
     pushed = false;
 }
 

}

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
2

Answer by illwunn · Aug 15, 2011 at 09:26 PM

Why would u not just make the elevator refrence a global variable? Like this:

 Elevator myElevator;

 void Start() {
     myElevtaor = GetComponent<Elevator>();

 }

that way you can access it anywhere in the button script?... or am i missing sumthing?

Comment
Add comment · Show 2 · 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 Rennat · Aug 15, 2011 at 09:29 PM 0
Share

It needs the public keyword but this is the right way to cache a script reference.

avatar image illwunn · Aug 15, 2011 at 09:30 PM 0
Share

ya sorry, if u wanted to access it outside of the button class jus make the variable public

avatar image
0

Answer by cernst77 · Aug 15, 2011 at 09:31 PM

I wanted to try this but, being a newbie, I was probably botching the syntax of what you have. Visual Studio was red underlining it. I have to pack up and go home before I try what you have there, I'll try it when I get home and see if your syntax works, thanks.

Just a reminder, I need to be able to access GoToFloor on Elevator, that declaration will work for that?

Comment
Add comment · Show 2 · 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 illwunn · Aug 15, 2011 at 09:35 PM 0
Share

yep, as long as the GoToFloor function is public you can jus type in myElevator.GoToFloor(); and that shud call the function properly

avatar image Rennat · Aug 15, 2011 at 09:35 PM 0
Share

Please don't use Answers to expand your Question or to reply to an Answer. Editing your question and adding new pertinent information is the correct way to let people know there is more you need to know. Answers are not sorted chronologically because they are not meant to be used as a forum.

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.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Distribute terrain in zones 3 Answers

how can i add another scripts functionality to a button on another script? 2 Answers

Multiple Cars not working 1 Answer

Button's sprite swap works fine but it doesn't change the related image's source image! why? 1 Answer

Change button icon for each without multiple GUISkins 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