Henlo, i’m fairly new to C# and Unity and was trying to scale my background along with the Canvas without using anchor point and breaking the pixel (stretching, etc)
I figured out a basic formula that will help me solve the task by scaling the renderTexture .
By dividing the “new” RectTransform in Update , with “old” RectTransform in Start , in my case it was 3840 / 1920 = 2 (3840 is default resolution Start and 1920 after i changed the resolution UPDATE)
I then will use the “result” for the scaling, thus matching the canvas size .
It works in theory and manual adjustment, but i can’t get the code to work for automation .
the code did compile but Unity editor gave out an error "
NullReferenceException: Object reference not set to an instance of an object
MenuBackgroundScaler.Update () (at Assets/Scripts/MainMenu/MenuBackgroundScaler.cs:45)
".
I understand that this error is referencing to a null/empty variable .
“oldrt” to be exact .
I think the problem comes down to me not knowing how to use a result from Start and bring it to Update
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class MenuBackgroundScaler : MonoBehaviour
{
public Canvas canvas;
public GameObject menubackground;
private RectTransform oldrt;
void Start()
{
//Fetch the RectTransform from the GameObject
canvas = gameObject.GetComponent<Canvas>();
Debug.Log (canvas.enabled);
//old canvas size
RectTransform oldrt = canvas.GetComponent<RectTransform>();
oldrt.sizeDelta = new Vector2(oldrt.sizeDelta.x, oldrt.sizeDelta.y);
}
void Update()
{
//getting the rect values
RectTransform rt = canvas.GetComponent<RectTransform>();
//formula
if (rt.sizeDelta == new Vector2(3840f, 2160f) || rt.sizeDelta == new Vector2(5120f, 2160f))
{
menubackground.transform.localScale = new Vector3(oldrt.sizeDelta.x/rt.sizeDelta.x, oldrt.sizeDelta.x / rt.sizeDelta.x, oldrt.sizeDelta.x / rt.sizeDelta.x);
}
else
{
menubackground.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
}
}
}
Note: i could just put in the actual result, but doing so mean i will have to manually calculate for all the different resolution, plus i’m still in the process of learning, so knowing how to get this to work would be nice, please help