简体   繁体   中英

How to make a transform.position affect more than one GameObject

I'm currently working on a mobile game.

I've coded the transform.postion to use Mathf.PingPong, So when the image hits the side of the screen it will bounce off and keep going.

However I've gotten it to work, I want like 20 GameObjects doing the same thing but in different positions without having 20 scripts.

using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;


public class PingPongEffect : MonoBehaviour
{

    public float speed = 9.0f;

    void Update()
    {
        transform.position = new Vector3(Mathf.PingPong(Time.time * speed, 1920), transform.position.y, transform.position.z);
        transform.position = new Vector3(transform.position.x, Mathf.PingPong(Time.time * speed, 1080), transform.position.z);
    }

}

Here is a visual video for reference https://youtu.be/_e15PaijQi0

Transform.Position is only able to manipulate one gameObject at a time, unless you group other objects under that Transform . But in reality only still that GameObject will move and the others will move only because they are grouped under one hierarchy, so because of this many of your viruses would go offscreen.

So if i were you i would just insert the same 20 prefabs to the screen. I guess your concern is performance which in this case is neglible, however if it's some strange of requirement you could alternatively do this.

Tag all your Virus GameObjects with the tag "Viruses", or make the list public and assign them directly from the editor, then use the script below

public class PingPongEffect : MonoBehaviour
{

    public float speed = 9.0f;
    List<Transform> viruses = new List<Transform>();

    void Awake()
    {
        var virusGameObjects = GameObject.FindGameObjectsWithTag("Viruses");
        foreach(var virusGameObject in virusGameObjects)
        {
            viruses.Add(virusGameObject.transform);
        }
    } 

    void Update()
    {
        foreach(var virusTransform in viruses)
        {
            virusTransform.position = new Vector3(Mathf.PingPong(Time.time * speed, 1920),
                virusTransform.position.y, virusTransform .position.z);
            virusTransform.position = new Vector3(virusTransform .position.x, 
                Mathf.PingPong(Time.time * speed, 1080), virusTransform .position.z);
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM