简体   繁体   中英

Change the scale of a gameObject that is not instantiated in a script in unity

In an empty scene i add an empty gameObject and call it "script". I attach a C# script that creates a texture object and put a sprite renderer on that. A webcam image is rendered. I want to change the scale with which the sprite is displayed. This change is already possible manually through the inspector->transform->scale of the script gameObject. However, I want to change only one parameter and hence i need to add a public parameter into the script. How do i - from the script - access the tansform scale of the empty script eventhough there is no such gameObject instantiated within the script?

using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.InteropServices;

[RequireComponent(typeof(SpriteRenderer))]
public class contours : MonoBehaviour
{

    SpriteRenderer rend;
    void Start()
    {
        tex = new Texture2D(432, 240, TextureFormat.RGBA32, false);
        rend = GetComponent<SpriteRenderer>();
    }

    void Update()
    {
        pixel32 = tex.GetPixels32();        
        //get a customized texture here
        tex.SetPixels32(pixel32);
        tex.Apply();

        //create a sprite from that texture
        Sprite newSprite = Sprite.Create(tex, new Rect(0, 0,432,240), new Vector2(0.5f, 0.5f), 100F, 0, SpriteMeshType.FullRect);

        rend.sprite = newSprite;
}

在此处输入图像描述

The reference to the Transform component of the very same GameObject a component is attached to is a built-in property transform . In general you could eg do

rend.transform.localScale = newLocalScale;

However, in your case your own script is attached to the same GameObject as well so all you need to do is

transform.localScale = newLocalScale; 

Btw there is also no need whatsoever to create a new Sprite instance every frame ! Altering the texture will automatically also update the Sprite based on that texture!

And even then still questionable why you would change all the pixels of a texture every frame..

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