Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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
0
Question by saddragon · Jul 26, 2021 at 02:33 PM · gameobject2d game

How do I make a script only affect one gameobject 2D

I've scoured various forums and websites, and I haven't found anything that works. I have a script attached to multiple game objects, technically several scripts but whatever. Point is, even though these are separate game objects, they still do the same thing even when the player is only interacting with one of the objects. (The game objects in question are npcs, and when the player talks to one they are supposed to stop walking and start talking. But all of the npcs do that). Please help. I feel like I have tunnel vision or stress or whatever, so I can't think straight and I'm getting super stressed out for this hopefully simple fix.

 [RequireComponent(typeof(BoxCollider2D))]
 
 public abstract class Interactable : MonoBehaviour
 {
     public bool isInteracting;
     public abstract void Interact();
 
     void Awake()
     {
         isInteracting = false;
     }
     private void Reset()
     {
         GetComponent<BoxCollider2D>().isTrigger = true;
     }
     private void OnTriggerEnter2D(Collider2D other)
     {
         isInteracting = true;
         if (other is BoxCollider2D && other.CompareTag("Player"))
         {
             other.GetComponent<PlayerMovement>().StartInteraction();
         }
     }  
     private void OnTriggerExit2D(Collider2D other)
     {
         isInteracting = false;                
         if (other is BoxCollider2D && other.CompareTag("Player"))
         {
             other.GetComponent<PlayerMovement>().StopInteraction();
         }
     }
 }
 public class DialogueUI : MonoBehaviour
 {
     [SerializeField] private GameObject dialogueBox;
     [SerializeField] private TMP_Text textLabel;
     private Typewriter typewriter;
     public static bool dialogueStarted;
 
     private void Start()
     {
         dialogueStarted = false;
         typewriter = GetComponent<Typewriter>();
         CloseDialogueBox();
     }
     public void StartDialogueUI()
     {
         if (dialogueStarted == false)
         {
             dialogueBox.SetActive(true);
         }
     }
     public void ShowDialogue(DialogueObject dialogueObject)
     {
         StartCoroutine(StepThroughDialogue(dialogueObject));
     }
     private IEnumerator StepThroughDialogue(DialogueObject dialogueObject)
     {
         foreach (string dialogue in dialogueObject.Dialogue)
         {
             yield return typewriter.Run(dialogue, textLabel);
             yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.R));
         }
         dialogueStarted = false;
         CloseDialogueBox();
     }
     public void CloseDialogueBox()
     {
         dialogueBox.SetActive(false);
         textLabel.text = string.Empty;
     }
 }
 public class NPCSpeaking : Interactable
 {
     private static DialogueUI dialogueUI;
     [SerializeField] public DialogueObject[] npcDialogue;
     public int iterations = 0;
     [SerializeField] public int speakerNumber;
 
     private void Awake()
     {
         dialogueUI = FindObjectOfType<DialogueUI>();
         isInteracting = false;
     }
     public void PlotDevelopment()
     {
         iterations++;
     }
     public override void Interact()
     {
         dialogueUI.StartDialogueUI();
         StartDialogue();
     }
     public void StartDialogue()
     {
         if (DialogueUI.dialogueStarted == false)
         {
             DialogueUI.dialogueStarted = true;
             dialogueUI.ShowDialogue(npcDialogue[iterations]);
             Debug.Log("dialogueui");
         }
     }
 }
 public class NPCMovement : MonoBehaviour
 {
     bool facingRight = true;
     public float speed;
     private Animator anim;
     static bool isMoving;
     public float distance;
     internal Transform thisTransform;
     internal Vector3[] moveDirections = new Vector3[] { Vector2.right, Vector2.left };
     internal int currentMoveDirection;
     bool isOnGround = false;
     public float slopeFriction;
     public LayerMask whatGround;
     float i;
     Vector3 Scaler;
     public static float npcRotation;
     private PlayerMovement player;
     int f = 0;
 
     public void Awake()
     {
         i = distance;
         isMoving = true;
         currentMoveDirection = 0;
         anim = GetComponent<Animator>();
         thisTransform = this.transform;
         Scaler = transform.localScale;
         player = FindObjectOfType<PlayerMovement>();
     }
     void NormalizeSlope()
     {
         if (isOnGround)
         {
             RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up, 1f, whatGround);
             if (hit.collider != null && Mathf.Abs(hit.normal.x) > 0.1f)
             {
                 Rigidbody2D body = GetComponent<Rigidbody2D>();
                 body.velocity = new Vector2(body.velocity.x - (hit.normal.x * slopeFriction), body.velocity.y);
             }
         }
     }
     void Update()
     {
         NormalizeSlope();
         if (DialogueUI.dialogueStarted == false)
         {
             if (i > 0)
             {
                 isMoving = true;
                 thisTransform.position += moveDirections[currentMoveDirection] * Time.deltaTime * speed;
                 i -= Time.deltaTime;
             }
             if (i < 0)
             {
                 i = distance;
                 ChooseMoveDirection();
                 Flip();
             }
         }
         else
         {
             isMoving = false;
             if (npcRotation == player.playerRotation)
             {
                 Flip();
                 f += 1;
             }
         }
         if (DialogueUI.dialogueStarted == false && f == 1)
         {
             Flip();
             f -= 1;
         }
         anim.SetBool("walking", isMoving == true);
     }
     void ChooseMoveDirection()
     {
         if (facingRight == false && currentMoveDirection == 1)
         {
             currentMoveDirection = 0;
         }
         else if (facingRight == true && currentMoveDirection == 0)
         {
             currentMoveDirection = 1;
         }
     }
     void Flip()
     {
         facingRight = !facingRight;
         Scaler.x *= -1;
         transform.localScale = Scaler;
         npcRotation = Scaler.x;
     }
 }

Comment
Add comment · Show 3
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 Llama_w_2Ls · Jul 26, 2021 at 02:40 PM 0
Share

Yes, please send the script. If your script is set up correctly, it should only interact with that instance of the script, referring to that specific NPC. For example:

 public class NPC : MonoBehaviour
 {
      // Reference to the specific NPC game object
      public GameObject npc;
 
      public void TalkTo()
      {
           // ...
 
           // Do stuff with 'npc' object (will only affect that game object)
      }
 }
avatar image logicandchaos Llama_w_2Ls · Jul 26, 2021 at 06:02 PM 0
Share

why create a reference to npc on the NPC script you can just use gameObject, the built in reference..

avatar image saddragon · Jul 26, 2021 at 02:55 PM 0
Share

I've since added the most relevant scripts. Sorry for those who want to help and now have to dig through this monstrosity.

3 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by GorseB · Jul 26, 2021 at 11:28 PM

It's because all your NPC's are looking at the same DialogueUI class to check whether dialogue with them has started, because on the Awake() method of the NPCMovement class you are doing dialogueUI = FindObjectOfType<DialogueUI>(); which will return the first instance of DialogueUI in the scene, you should instead do dialogueUI = gameObject.GetComponent<DialogueUI>(); and ensure each NPC has a DialogueUI script attached to their game object

Good Luck!

Comment
Add comment · Show 4 · 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 saddragon · Jul 27, 2021 at 12:12 AM 0
Share

The npcs keep moving and while the speech "bubble"pops up, no text does.

avatar image GorseB saddragon · Jul 27, 2021 at 12:53 AM 0
Share

did you add a "typewriter" and assign a text field to each npc?

avatar image saddragon GorseB · Jul 27, 2021 at 02:03 AM 0
Share

Ah, that fixed the text issue. But the npcs still are moving.

avatar image saddragon · Jul 27, 2021 at 02:35 AM 1
Share

Ah never $$anonymous$$d, found another bug. But otherwise, that worked! I feel like an idiot now, because for some reason I told myself that I couldn't code it like that, but now I can with no issues, so I don't know why I was being stupid. But seriously, thanks! Sometimes I need someone else to pull me out of my tunnel vision lol.

avatar image
0

Answer by logicandchaos · Jul 26, 2021 at 06:05 PM

I think this is the issue: static bool isMoving; in NPCMovement static variables are shared among all instances. So if you set isMoving to false than all NPCs stop moving. Same with all your other static references. You have to make these values non static to set individually for each NPC.

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 saddragon · Jul 26, 2021 at 11:17 PM 0
Share

I set all static variables to non static. It didn't fix it :( Could it be anything else?

avatar image
0

Answer by Jackson_365 · Jul 27, 2021 at 01:45 PM

Unity game manager. Script works only one time I'm making simple game manager. I have a script, which will be accessible from all scenes in the game. And I need to check values of its variables after loading new scene. But my code runs only once after starting the simulation while an object with this script exists in all scenes.

AdvancedMD

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

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

220 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 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 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 can I track if GameObject is null in function? 2 Answers

Setting GameObjects inactive/invisible by default in GUI? 2 Answers

How to place many or array of collectables with organized distance from each other and by doing it easy way? 0 Answers

Find GameObject with value within script 2 Answers

continous movement for rigidbody2d using addforce with buttons 2 Answers


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