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

Time:01-15

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;
}

enter image description here

CodePudding user response:

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 e.g. 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 ..

  •  Tags:  
  • Related