#archived-code-general

1 messages ยท Page 137 of 1

gray mural
#

first of all you have TextMeshProGUI, you need TextMeshProUGUI

leaden ice
#

is this supposed to be UI or not?

#

oh yeah also this is just a compile error

#

because you spelled the class name wrong

half sparrow
#

I just want labels on my tiles. For example tile at position x=0 y =0 will have the label 1 and so on (2,3,....25)

leaden ice
#

you need to decide if this is UI or not and give it the apporopriate components

#

there's also no reason to be calling AddComponent

#

just put the appropriate components on the prefab

leaden ice
#

or game world objects

half sparrow
#

gameobjects

leaden ice
#

everything is a GameObject

#

are they UI or game world objects

gray mural
leaden ice
#

if they're not UI, don't use UI stuff like TextMeshProUGUI

#

you can use the game world version of that - TextMeshPro

half sparrow
leaden ice
#

this picture tells us little

#

because we can't see whhat components are on everything

gray mural
#

yes, you need TextMeshPro - Text

#
[AddComponentMenu("Mesh/TextMeshPro - Text")]

public partial class TextMeshPro : TMP_Text, ILayoutElement { ... }
#

this is for non-UI GameObjects

half sparrow
#

Let's forget my stuff. Lets assume you want to create a grid 5x5 with tiles (square sprites) and have a label on the middle as number. the first tile has number 1 and the 25th tile has number 25. How am i supposed to do this? Because the text i get is from UI. Right click ->> UI --> Text - TextMeshPro

#

All this by code only

gray mural
half sparrow
#

no i dont. I want to be like land where my player will walk

#

or maybe there is another prespective i cant see

gray mural
leaden ice
#

3D -> TextMeshPro

gray mural
half sparrow
#

Would y like to share my screen to see what i have done? Or its not possible right now?

gray mural
peak halo
#

Yeah that sounds really reasonable thank you so much for the input! I think I am going to sleep on it though and see what I can come up with in the morning. Maybe like a hybrid solution? idk

Anyway thanks a lot! Really appreciated

ashen yoke
#

@half sparrow non ui TMP is in world space

#

it has a world position if its behind the tile it wont be rendered

half sparrow
#

Now i understood

ashen yoke
#

check position, if its actually anywhere near the tile

half sparrow
#

I used 3D Object --> TextMesh

#

and now it spawns

#

i will send a screenshot in a sec

gray mural
ashen yoke
#

tiles are sprites

half sparrow
#

I dont know but in 2d gameobject there is no text

#

(Generally i am new in Unity)

ashen yoke
#

2d and 3d are both 3d

#

there are various systems that differ

#

but essentially 2d is just 3d meshes

#

so in both the 3d text will function identically

half sparrow
#

Ok thanks guys. Now i have to adjust the location the the color

echo plaza
#

Hey @leaden ice, I finally got it so the rebinding works in game! I made a custom script that adds the new keybinds to the player's PlayerInput. Along with this I edited a bunch of the rebinding sample's scripts to make it so this actually worked. And now I can finally relax and know that my players can change their keybinds if they wish. Also I can add more controls and their rebinding really easily now. Thanks for the help! :)

hollow hound
#

What are common practices for managing subscription for events?

I have player that is spawn in Awake of a spawner after the game start.
I have UI component that subscribes to player events in onEnable.
There is chance that player will spawn after UI component onEnable which results in null reference exeption.

Current realisation:
UI components subscribes to GameManager event onPlayerInit.
Player spawner spawns player in Awake and than invokes onPlayerInit in Start..
That way UI components starting subscription to player events after player is spawn.

The problem is that GameManager is singleton. So to access instance of GameManager it need to complete its Awake. But UI components onEnable can execute before GameManager Awake and nullReferenceExeption again.
How I can resolve this problem?

I don't want to mess with seo.
I want to avoid subscribtion to events in Start, because that way I still should duplicate code in onEnable with kludgy checks.
I want to avoid spawning all UI components (and other thing) by hands in one spawner with specific order.

ashen yoke
#

will save you lots of headaches

modest pawn
#

Try DefaultExecutionOrder attribute on gamemanager, awake should e running before any onenable

ashen yoke
#

that will only alleviate some scenarios

#

i.e. the startup, at runtime you will be running into complex scenarios where observed objects get instantiated, you need to observe it, its components, then unsubscribe in the same order, and keep track of it all

#

this all is alleviated with event bus conceptually

#

you dont need to know what you observe UI just receives events from the bus

#

can subscribe at any point, doesnt matter if the observable exists or not, what order it all stops mattering

hollow hound
#

If understand correclty, GameManager is doing this "bus" concept. It trigers events for ui only after player is created. The problem is that GameManager is monobeheviour sigleton so its instance can be null on Enable of other components.
Should I do similar logic but for static bus class?
Or I should just invoke several events one after another like: playerSpawn, uiSubscribe, etc?

ashen yoke
#

well separation of concerns aside, you can set your GameOverlord high in SEO if its the root system, there are other ways to ensure that it always loads first even before any awake is called but its advanced

modest pawn
#

I understand the pattern, but the observable cant be null when you subscribe to it.

ashen yoke
#

elaborate please

modest pawn
#

It's the lack of order of initialization that puzzles me. Observables have to be not null if you want to sub functions to them. In other words, GameManager must exist. Then some game data like a player must be initialized before invoking the UI events.
Something like InitManager->InitGameData->InvokeOnEvent. If this is not right I am clearly not seeing something.

compact spire
#

If I want a rigidbody to rotate towards a target using torque, I'm guessing I need to do some math between the rotation of the object to be torqued and the position of the target and then.. normalize that value? I can't find too many concrete examples of this besides some implementations of a PID, which is a bit overkill.

icy pebble
#

@ashen yoke considering how many times today you've mentioned "event bus" i'm surprised you don't have a go to "use this" ๐Ÿ˜†

ashen yoke
# modest pawn It's the lack of order of initialization that puzzles me. Observables have to be...

yes you are missing couple of things, 1 here game manager functions as event bus, but it actually has a lifetime so you are bumping first time into waiting for object to init,
with event bus its always there, 2. the game manager here is not the observable, the player is and the ui needs a way to be notified of when the observable is spawned to hook,
which is alleviated if there is no need to hook into a particular observable, all ui would care is what events it receives to update corresponding parts, ie subscribing to

EventBus<OnPlayerDamage>.Subscribe(HandlePlayerDamage)

wont need an active Player

icy pebble
ashen yoke
#

@icy pebble im surprised myself, this is first time in a long time i had to mention it, and so many times a day in row because people keep coming with the same issue type

icy pebble
#

funny

ashen yoke
#

i dont like it

#

ยฏ_(ใƒ„)_/ยฏ

icy pebble
#

do you have one that you do like, or a reason you don't like it?

#

i have no frame of reference here

ashen yoke
#

looks too convoluted, no clear event naming, strongly typed payload, no arbitrary event sub, too verbose, too many interfaces

#

i have one that i like its the one i wrote ๐Ÿ˜„

#

example

icy pebble
ashen yoke
#
public struct OnPlayerReceivedDamage : IEvent
{
    public float damage;
}
//...
// whole file with clearly named events all searchable by IEvent
class SomeMono : MonoBehaviour
{
      private EventBinding<OnPlayerReceivedDamage> _onPlayerReceivedDamage;
      
      void Awake(){
          _onPlayerReceivedDamage = HandlePlayerReceivedDamage;
      }
      
      void OnEnable()
      {
          _onPlayerReceivedDamage.Listen = true;
      }  

      void OnDisable()
      {
          _onPlayerReceivedDamage.Listen = false;
      }  
    
      void HandlePlayerReceivedDamage(OnPlayerReceivedDamage payload)
      {
          txt.SetText(payload.damage);
      }
}
#

then somewhere

#
EventBus<OnPlayerReceivedDamage>.Raise(new OnPlayerReceivedDamage(){ damage = 1 });
#

minimal baggage, minimum interfaces, they are still there, but simplicity and clarity is what i like, easy to reason about easy to track

compact spire
#

Unity has a built in event system doesn't it? What's the issue with that?

ashen yoke
#

never thought of that, did you know any scenario where it was used as an event bus for arbitrary data?

#

arbitrary events

restive hound
#

Does Physics.Checkbox check evenly from the origin
(i.e. if casted at origin, bottom would be -2 top would be 2 for a half value of 2)
or does it cast upwards i.e. box would check 0 to 4?

icy pebble
#

Does a lot with the editor UI but I assume you can also do a lot in code. Just haven't found a clear example yet.

ashen yoke
#

its unrelated

#

its is simply a serialized delegate

jagged rock
#

I wonder if there are many people who have played with the new Spline Package and can understand what is causing this issue? https://gamedev.stackexchange.com/questions/206196/unity-spline-animate-reset-the-position-when-change-the-speed

marble holly
#

hey,
if (Application.internetReachability == NetworkReachability.NotReachable) does not working on StandAlone windows il2cpp build, correctly ...
any suggestions?
thanks.

icy pebble
steady moat
# hollow hound What are common practices for managing subscription for events? I have player t...

You did not correctly implement the pattern. When ever you reference the GameManager, this is when it should instantiate itself if it has not.

using UnityEngine;

// <> denotes this is a generic class
public class GenericSingleton<T> : MonoBehaviour where T : Component
{
    // create a private reference to T instance
    private static T instance;

    public static T Instance
    {
        get
        {
            // if instance is null
            if (instance == null)
            {
                // find the generic instance
                instance = FindObjectOfType<T>();

                // if it's null again create a new object
                // and attach the generic instance
                if (instance == null)
                {
                    GameObject obj = new GameObject();
                    obj.name = typeof(T).Name;
                    instance = obj.AddComponent<T>();
                }
            }
            return instance;
        }
    }

    public virtual void Awake()
    {
        // create the instance
        if (instance == null)
        {
            instance = this as T;
            DontDestroyOnLoad(this.gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }
}

https://awesometuts.com/blog/singletons-unity/

simple egret
#

A little side note, as the conversion to T in Awake is never supposed to fail, a hard-cast should be used.
instance = (T)this;

hollow hound
steady moat
hollow hound
#

Because

if (instance == null) {... }
else Destroy(gameObject);
steady moat
#

instance = obj.AddComponent<T>(); will only set after the Awake OnEnable

hollow hound
#

We can't know this for sure.
It was accessed before its Awake so the instance is already created.

icy pebble
#

@ashen yoke watched a few more videos. Unity events are pretty tied to the editor and would be hard to use in very large or complex projects. A bus system is probably better for what I'm ultimately doing.

steady moat
hollow hound
steady moat
#

Where do you see the destroy ?

#

instance is null at this point.

hollow hound
#

else Destroy(gameObject);

steady moat
#

It will not do the else...

#

If it is null.

#

instance is only set after the component as been initialize.

#

Which happens in the line instance = obj.AddComponent<T>();

#

Which is kinda redondant though.

hollow hound
# steady moat If it is null.

But its not null because it was accessed from another class before its Awake. And by accessing it, instance was created, right?

steady moat
#

because you assign it also in the awake.

steady moat
#

Do you understand the difference between instance and Instance ?

hollow hound
#

Yes

steady moat
#

Then, you should understand that instance is null in the Awake while we do the call to Instance.

#

Ask yourself, when is instance set ?

#

Would the Awake run before, or after it is set ?

hollow hound
#

I thought here:
instance = obj.AddComponent<T>();
Am I wrong?

steady moat
#

AddComponent will make the Awake call before returning.

hollow hound
#

Oh, I totally missed this part

#

Thanks

hollow hound
steady moat
#

If you need serialized data, you use a prefab that you instanciate.

#

With the usage of Resources.Load

warm geyser
#

Hey I have a general logic question, I have a set of 3 options that can be picked in any order, I just need to figure out whatever the 3rd option is that the first two options aren't. Ideally without just spamming if/else statements. So for example, let's say I have 3 options:

Apple, Pear, Banana

And for my first choice I pick Apple, and for my second choice I pick Banana, the third choice will HAVE to be Pear.

Likewise, if my first choice is Banana, and my second choice is Pear, my third choice by default will be Apple.

Basically what is the easiest way to do process of elimination on the final choice in a table of 3 data elements

steady moat
steady moat
hollow hound
steady moat
#

However, if someone else does the call to Instance before it is. It will be destroyed,

simple ridge
#

Hi everyone, just wondering how would I go about subscribing an Action<bool> to a UnityEvent<bool>? The action is being set using a lambda expression that i want to have the ability to remove the listener or change it at a later date. Is this possible?

So far tried it and am getting the error, System.Action<bool> is not assignable to parameter type UnityEngine.Events.UnityAcrion>bool>

hollow hound
steady moat
simple ridge
steady moat
hollow hound
# steady moat Usually, you do not have a singleton inside the scene. It is created at runtime.

Currently I have GameManager(singleton) on the scene that is holding list of characters. Some buttons are created for starting screen based on this list. After character selection new scene is loaded and player is spawn based on GameManager.CurrentCharacter.
What would be better approach to this?
Should I move these lists to scriptable object and loading them with resource.Load in GameManager?
Should I remove GameManager from the scene and spawn it somehow when the game starts?

warm geyser
#

Thank you

steady moat
simple ridge
blazing smelt
#

I made a custom package and imported it, but the project doesn't recognise my namespace. How would I go about solving this?

versed marsh
#

Hey, I'm trying to get this very specific vector from two points but im not exactly sure how. I tried visualizing it using this terrible graphic if it helps at all, but I'm honestly not sure where to start.

buoyant crane
lean sail
#

if its 3D, you'll need some other factor to determine which way that line should point. Because you could rotate that desired vector around the imaginary line and each rotation would still be perpendicular

versed marsh
#

Right, I think I'm gonna just make a vector2 for the sun and for the planet only using the axis' i care about

upbeat hill
#

Hey guys, I'm messing around with the 3D Game Kit, I'm trying to add another transition from Idle to Ellen getting her weapon out. I've set a parameter IsAiming to false by default and I'm trying to trigger the animation by pressing the right mouse button and setting isaiming to true but it does not work =/

#

Looking at the PlayerInput/PlayerController, there is so much there that it gets overwhelming pretty fast to set a simple animator transition

#

I'm making progress on understanding those scripts, I feel I'm getting close, but no luck so far, hmu by @me if you're interested in the matter

limber agate
analog echo
#

Is there smth I'm missing?

I want to search for every document inside of 'mails' but this is not finding any document (using Firestore Database)

Example of a Document Path I have:
/mails/DBLG58-RFAJFA-6BFNDT

Code:

CollectionReference mailsRef = db.Collection("mails");
await mailsRef.GetSnapshotAsync().ContinueWithOnMainThread(task =>
{
        QuerySnapshot mailsQuerySnapshot = task.Result;
        Debug.Log(mailsQuerySnapshot.Documents);
        foreach (DocumentSnapshot documentSnapshot in mailsQuerySnapshot.Documents)
        { 
            Debug.Log(String.Format("Document data for {0} document:", documentSnapshot.Id));
            Dictionary<string, object> mail = documentSnapshot.ToDictionary();
            foreach (KeyValuePair<string, object> pair in mail)
            {
                Debug.Log(String.Format("{0}: {1}", pair.Key, pair.Value));
            }
        });
}

This debug logs [ ] and not any of the documents
Debug.Log(mailsQuerySnapshot.Documents);

Log: Firebase.Firestore.DocumentSnapshot[]

versed marsh
# buoyant crane looks like you can get the direction of the line from `planet.position - sun.pos...

Thanks so much for your response, I ended up with this (inside FixedUpdate) and it works just as I needed

Vector2 orbitPos = new Vector2(transform.position.x, transform.position.z);
Vector2 planetPos = new Vector2(planet.transform.position.x, planet.transform.position.z);
Vector2 dir = Vector2.Perpendicular(planetPos - orbitPos);
Vector3 velocity = new Vector3(dir.x, planet.rigidbody.velocity.y, dir.y);
planet.rigidbody.velocity = velocity * planet.rotationSpeed;
#

That being said, I am now encountering this strange issue where the planets seem to get farther and farther away from their respective orbit points, and I'm not sure why

steady moat
#

Given an initial speed

wind palm
compact spire
#

So I'm intermittenly getting an excepton when I run my project. It makes me think that I have a race condition when looking up gameobjects/components before they are initialized, but I'm not sure how to isoalate it down. ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <582c35e8f45345d395e99f8e72e3c16d>:0)

#

I just realized that debug isn't automatic in Rider....

#

I'm used to VS where the swap between debug and release dictates whether or not what happens when you click build and run.

#

I had Rider set to "attach to unity editor and play" and then I would hit the play button thinking that I would get a break point on exception. I didn't notice the little debug button on the right.

dapper schooner
#

QQ, Is it required to rebuild my unity app every time I create a new addressable post release? Even if the app already has the buttons setup to download the new addressable by name.

rugged storm
#

yo I have this script that makes a dictionary of classes inheriting from element https://pastebin.com/jWnWR0bg, however,

im getting a "NullReferenceException: Object reference not set to an instance of an object" error on the first line of the constructor of the first class it runs line 36 on
if (Activator.CreateInstance(type) is Element element)

#

this wasn't happening before a slew of changed i made so some other underlying logic but now of that logic effects this script of the element's constructors so I have no idea why its happening now.

#

am i not allowed to run Activator.CreateInstance(type) in a static method?

buoyant crane
#

Planet Orbits

compact spire
#

eww reflection

#

What you are doing seems to be beyond my limited skillset.

#

What part is actually throwing the null? type I'm guessing?

rugged storm
#

No nothin in that is throwing null,

compact spire
#

What in the stack trace is null then

rugged storm
#

It claims to be happening on the first line of type's constructor

compact spire
#

oh when it's trying to create an instance

rugged storm
#

yeah

tepid juniper
#
  // Creating and sending web request
        using (UnityWebRequest request = UnityWebRequestTexture.GetTexture(url)) {
            request.SetRequestHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            request.SetRequestHeader("Pragma", "no-cache");
            request.SendWebRequest();
            while (!request.isDone || interruptToken.IsCancellationRequested) {
                if (interruptToken.IsCancellationRequested) {
                    Debug.Log("Task {0} cancelled");
                    request.Abort();
                    interruptToken.ThrowIfCancellationRequested();
                }
                await UniTask.Yield();
            }
            if (WebRequestError(request)) {
                Debug.LogWarning($"Error while downloading resource < {url} >, error: {request.error}");
                return null;
            }
            Texture2D texture = ((DownloadHandlerTexture)request.downloadHandler)?.texture;
            if (texture is null || texture.width == 0) {
                Debug.LogWarning($"Error while downloading resource < {url} >, error: Download result was null");
                return null;
            }

Greetings. My question is with downloading .astc files with webrequests. I am trying to donwload already astc compressed image, but I always getting texture = null, as if there would be no image data. What could be the cause? this code works with png without problems.

Thank you in advance

rugged storm
#

NullReferenceException: Object reference not set to an instance of an object
Sand..ctor () (at Assets/Elements/Solids/Sand.cs:11)
System.Reflection.RuntimeConstructorInfo.InternalInvoke (System.Object obj, System.Object[] parameters, System.Boolean wrapExceptions) (at <4a4789deb75f446a81a24a1a00bdd3f9>:0)
Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation.
System.Reflection.RuntimeConstructorInfo.InternalInvoke (System.Object obj, System.Object[] parameters, System.Boolean wrapExceptions) (at <4a4789deb75f446a81a24a1a00bdd3f9>:0)
System.RuntimeType.CreateInstanceMono (System.Boolean nonPublic, System.Boolean wrapExceptions) (at <4a4789deb75f446a81a24a1a00bdd3f9>:0)
System.RuntimeType.CreateInstanceSlow (System.Boolean publicOnly, System.Boolean wrapExceptions, System.Boolean skipCheckThis, System.Boolean fillCache) (at <4a4789deb75f446a81a24a1a00bdd3f9>:0)
System.RuntimeType.CreateInstanceDefaultCtor (System.Boolean publicOnly, System.Boolean skipCheckThis, System.Boolean fillCache, System.Boolean wrapExceptions, System.Threading.StackCrawlMark& stackMark) (at <4a4789deb75f446a81a24a1a00bdd3f9>:0)
System.Activator.CreateInstance (System.Type type, System.Boolean nonPublic, System.Boolean wrapExceptions) (at <4a4789deb75f446a81a24a1a00bdd3f9>:0)
System.Activator.CreateInstance (System.Type type, System.Boolean nonPublic) (at <4a4789deb75f446a81a24a1a00bdd3f9>:0)
System.Activator.CreateInstance (System.Type type) (at <4a4789deb75f446a81a24a1a00bdd3f9>:0)
ElementManager.DiscoverAndAddElements () (at Assets/Elements/ElementManager.cs:36)
ElementManager.Initialize () (at Assets/Elements/ElementManager.cs:19)
GameLogic.Start () (at Assets/GameLogic.cs:48)

(Sand being a class which inherits from Element)

#

snipit from sand to show where its claiming there is a null object

#

if i comment out the element its happening with it will just happen on the next one so i think its happening with whatever the first one it hits is E,A, its happening will every element

compact spire
#

If you remove everything from the Sand constructor, does it get past it then?

rugged storm
#

nope

compact spire
#

maybe

#

load the assemblies before attempting to create the instances?

rugged storm
#

actually wait small development, it seemingly with the base element class

#

but nothing that derives from it

compact spire
#

Is element derived from anything?

rugged storm
#

wait wtf, IT ALL WORKS NOW

#

maybe it was just a build error in unity and no element is just a class of it's own

#

i literally just commented it all out then undid it, thats all ive done...

compact spire
#

lol

cobalt gyro
#
            RaycastHit2D[] circleCast = Physics2D.CircleCastAll(origin, radius, Vector2.right, targetObjects);// Checks area for specified targets
            
            float closestDetected = 100f;
            GameObject closestTarget = null;

            for (int i = 0; i < circleCast.Length; i++){
                
                RaycastHit2D[] lineCast = Physics2D.LinecastAll(origin, circleCast[i].collider.transform.position, mask);// Draws ray between parent object and potential target
                float distance = Vector2.Distance(origin, circleCast[i].collider.transform.position);// Gets distance between parent object and potential target
                if (lineCast.Length == 0 /*Wall check*/&& distance < closestDetected /*Closer than previous check*/ && circleCast[i].collider != self/*Avoid own colllider*/){
                    closestTarget = circleCast[i].collider.gameObject;
                    closestDetected = distance;
                }
                Debug.Log(closestTarget.transform.position.ToString() + distance.ToString());
            }

            if (closestTarget != null){
                return closestTarget;
            } 
            else{
                return null;
            }
        }``` For some reason this function keeps returning the object its attached to even though i explicitly tell it not to
quick remnant
#

Would TextMeshPro questions go here?

compact spire
#

@cobalt gyro your trying to raycast against a layermask that the parent object is a part of?

cobalt gyro
#

and now i see what the problem is

quick remnant
#

Cheers

simple ridge
#

Hi everyone, I was hoping someone could help with with a solution for copying the entire state of an animator and pasting it into another. To explain, I have an animated model that can be replaced during runtime, however the model has some level of animation running on it that I want to preserve. Since the way its set up means destroying the game object, and then respawning a new "almost" identical copy with the same animator (though somewhat nested in the heirachy from the base prefab) I want to copy the state of the animator before the deletion and then replace it on spawning in the new object. Is this even possible?

tepid juniper
#

ASTC DXT5 image downloading via webrequests

cobalt gyro
soft shard
# simple ridge Hi everyone, I was hoping someone could help with with a solution for copying th...

When you say "state", do you mean the progress/time of the currently playing state or literally generating new states in a new animator at runtime? To do the latter would require Editor-only code, so you wouldnt be able to make a build using it, If you want an "amost identical" copy at runtime, it sounds like you could just duplicate whatever animator controller your using, and make your changes there, and put the different controllers in an array to select from if you need more than 1 "almost identical" change, but I may not fully understand what your trying to do

void basalt
#

For my case, transitions didn't work because I needed to replicate exact single frame snapshots over and over. This didn't work for me because the transitions need to complete before the next state starts

#

But if you can allow the transition to fully complete every time you need to replicate it, then it's probably going to work fine.
You can use the Animator.Play function to resume the states. Check it's overloads.

tiny mantle
#

this logs that escape has been pressed, but it doesn't pause or resume

dusk apex
somber nacelle
#

are you certain you've assigned an object to the pauseMenu variable and are not perhaps getting a NRE?

dusk apex
dusk apex
#

This might not be the issue you're having but it should be something you're aware of as you test your game

tiny mantle
#

strill didn't work

dusk apex
tiny mantle
#

I put in Debug.Logs in pause and reumse statements and they aren't being logged, so it isn't going into the statements

dusk apex
#

Likely at least one is occurring if the outer is print.

tiny mantle
#
if (Input.GetKeyDown(KeyCode.Tilde)){
            Debug.Log("Pressed escape");
            if (GameIsPaused){
                Debug.Log("Resuming");
                Resume();
            }
            else{
                Debug.Log("Pausing");
                Pause();
            }
        }```
dusk apex
#

Show the console tab.

tiny mantle
#

there is nothing

dusk apex
#

Or the component isn't in the scene.

tiny mantle
#

so that would only leave the object being inactive

lapis sierra
#
    {
        Slider slider;
        TextMeshProUGUI text;
        public GameDefinition currentValues;
        public GameDefinition[,] stageMissions;
        private GameDefinition gameDefinitionRefrence;
        private int totalProgress;

        private void Start()
        {
            slider = GetComponent<Slider>();
            text = GameObject.Find("sliderText").GetComponent<TextMeshProUGUI>();
            slider.maxValue = 30;
            gameDefinitionRefrence = gameObject.AddComponent<GameDefinition>();
            gameDefinitionRefrence.DeclareVariables();

            Debug.Log(stageMissions[0, 0].buttonPrices[0,0]);
            if(currentValues != null)
            {
                currentValues = stageMissions[GameDefinition.currentStage, GameDefinition.currentMission];
            }
            Debug.Log(GameDefinition.currentStage);
            Debug.Log(GameDefinition.currentMission);
            UpdateProgress();
        }```
This is a snipped of my code. I get a nul reference exeption in the `stageMissions` variable.
Its is created in this script but I dont think that I have the right reference.
#
    {
        // Score
        public static float score = 5000000;

        // Pointer to current Scene
        // Actually needs to be in another class
        public static int currentStage = 0;
        public static int currentMission = 0;

        public GameDefinition[,] stageMissions;

        public void DeclareVariables()
        {
            // Stage and Mission definition
            stageMissions = new GameDefinition[5, 10];

            // Create a new instance of GameDefinition and assign it to stageMissions[0, 0]
            GameDefinition gameDefinition = new();
            stageMissions[0, 0] = gameDefinition;

            // Price and Progress specified.
            stageMissions[0, 0].buttonPrices = new int[3,10]
            {
                { 100, 250, 500, 800, 1100, 1500, 2000, 2700, 3500, 5000 },
                { 300, 700, 1400, 2500, 4000, 9000, 14000, 19000, 27000, 35000 },
                { 5000, 7500, 12000, 20000, 31000, 50000, 100000, 150000, 250000, 500000 }
            };

            stageMissions[0, 0].buttonText = new string[3,10]
            {
                { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" },
                { "c", "g", "n", "y", "e", "i", "o", "s", "a", "e" },
                { "e", "l", "x", "t", "v", "z", "n", "d", "m", "q" }
            };

            stageMissions[0, 0].buttonProgress = new int[3] { 0, 0, 0 };
            stageMissions[0, 0].progressSlider = 0;
        }
    }```

This inherits from another class wich hold a few values:
```public class Values : MonoBehaviour
{
    public int[,] buttonPrices = new int[3,10];
    public string[,] buttonText = new string[3, 10];
    public int[] buttonProgress = new int[3];
    public int progressSlider;
}```
I have no idea what is wrong with this can somebody please help me.
somber nacelle
lapis sierra
#

In gameDefinition right?

somber nacelle
#

that's a different variable with the same name. i'm referring to the one in SliderBehaviour which is where your error is, no?

lapis sierra
#

currentValues = stageMissions[GameDefinition.currentStage, GameDefinition.currentMission];

tiny mantle
#

!code

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

somber nacelle
tiny mantle
#

also if you are going to put code into here, you can add syntax highlighting

#
Console.WriteLine("Hello World!");
lapis sierra
#

I dont assign it i can see

somber nacelle
#

exactly

#

that means it is null

lapis sierra
#
public void DeclareVariables()
        {
            currentMission = 0;
            currentStage = 0;```
If i put it like this it still doessnt work.
somber nacelle
#

huh? that's irrelevant to the issue. the array is null

#

if you want it to be a reference to the array on the GameDefinitions class then you need to assign it to that object stageMissions = gameDefinitionRefrence.stageMissions

lapis sierra
#

Omg that fixes that Isue thank you! But it brings out another one.

NullReferenceException: Object reference not set to an instance of an object
MyGameNamespace.SliderBehaviour.UpdateProgress () (at Assets/Scripts/BetterScripts/SliderBehaviour.cs:44)```
It says that it is in this snipped:
```cs
           
foreach (int indexValue in currentValues.buttonProgress)
            {
                currentValues.progressSlider += indexValue;
                totalProgress += indexValue;
                Debug.Log(indexValue);
            }```
somber nacelle
#

which is line 44

lapis sierra
#

oops

#

foreach (int indexValue in currentValues.buttonProgress)

#

That line

somber nacelle
#

then either currentValues is null or its buttonProgress variable is null

lapis sierra
#

Debug.Log(currentValues);
this give Null with uppercase. That is difrent from null right?

somber nacelle
#

that's unity's fake null, but that does mean that is the object that is null

lapis sierra
#

But we just assigned it

#
            if(currentValues != null)
            {
                currentValues = stageMissions[GameDefinition.currentStage, GameDefinition.currentMission];
            }
somber nacelle
#

keep in mind that you only assign to the first index of your 2d array. if those two ints you are using to index it are not both 0 then of course it will assign null to the variable

#

GameDefinition gameDefinition = new();
well that's a problem. this object is a MonoBehaviour. you should not be using new to instantiate a MonoBehaviour

lapis sierra
#

Ow in DeclareVariables?

somber nacelle
#

yes

lapis sierra
#

But it is in an inheritance does that make any diference?

somber nacelle
#

it's literally inheriting from MonoBehaviour. that is the entire issue with that line. does this object need to be a component in the scene? if not, then don't make the Values class inherit from MonoBehaviour

lapis sierra
#

No it does not have to I think

somber nacelle
#

of course that's only going to fix part of the issue. you'll still need to populate the rest of your array at some point

lapis sierra
#

It gives some other errors now

#

Assets\Scripts\BetterScripts\SceneCreatorTasks2.cs(65,50): error CS0311: The type 'Game.GameDefinition' cannot be used as type parameter 'T' in the generic type or method 'GameObject.AddComponent<T>()'. There is no implicit reference conversion from 'Game.GameDefinition' to 'UnityEngine.Component'.

somber nacelle
#

well of course, it's not a component anymore so why are you adding it as a component?

#

if it needs to be a component, then you have to use AddComponent to create an instance of it at runtime and it needs to inherit from MonoBehaviour again

lapis sierra
#

you are right

#

I dont think it has to be an component

#

It was a way to assign it to a reference so i could use itsfunctions

#

How can I assign the script to a variable? gameDefinitionRefrence = gameObject.AddComponent<GameDefinition>();

somber nacelle
#

you may want to rethink what exactly is happening here and what you are trying to accomplish with it

lapis sierra
#

Good idea. I think i have gotten too deep into it.

simple ridge
rare plank
#

Hello, is there a way to draw another vertical area underneath a vertical area?
https://sourceb.in/8oIeQccmwY - this is my code, however the 2nd vertical area seems to be drawn behind the first one

bold flare
#

Hi! cat_hi
I have a Cinematic property (sentence.cinematic) on a DialogueManager script, and it's working perfectly.
On game loading (if the player quits during a dialogue), the dialogue get back to the beginning, so I need to set the Cinematic property again. When I do that, and I try to active the cinematic gameobject, with sentence.cinematic.gameObject.SetActive(true);, I get an error, because sentence.cinematic is null, but it's appearing on the inspector (capture below).

This is a strange comportment, do you have any hypothesis?
Thanks!

(please mention me along with your response)

prime sinew
#

You can check by typing
t:DialogueManager in the hierarchy search bar

prime sinew
#

You searched with the t:, right?

bold flare
#

yep

#

But i found

#

I was writing my message

#

"Oh, ok, I'm dumb-
It was not null on my DialogueTrigger script, but it was on DialogueManager. It's difficult for me to explain it, cause I'm french, but if you want I can explain you the situation. Thanks!"

dim gust
#

hey i am trying to move the player away from a point where a ray hit but my issue is that the player is moveing away from the ground and into the void, how can i make it move up ?

merry shore
#

could do transform.up

dim gust
merry shore
#

transform.position += transform.up * speed * Time.deltaTime

dim gust
#

lerp would be better bc is smoother

dim gust
merry shore
#

๐Ÿ˜„

bold flare
#

Good morning! cat_hi

I need to set a variable when the game loads. This variable is of type Cinematic, and accepts a lot of classes heriting from "Cinematic". For example, I would like to set this variable to a script called Cinematic_e1c1. I can't use .Find (and don't want to), and the gameobject on which the script is attached is inactive on game launch. What's the solution? catthinking

Thanks!

spice cave
#

Hey!
How would i implement Spline points to perlinValue?
Lets say -1 to 0 goes from y = 80 to 100

gray mural
#

that doesn't matter anyway

#

As I have understood, you have problems with accessingCinematic_e1c1 reference, right? @bold flare

bold flare
bold flare
#

Cause in my save file, the solution I found is to save the component ID or name in a string.

gray mural
#

it's the best solution

#

unless your script is on prefab

bold flare
#

Wdym?
If I set the SerializeField attribute, then what?

gray mural
#

and you set your GameObject

#

you have said it's inactive

#

so it's in the scene

#

you can set it easily then

bold flare
#

But I can't

gray mural
bold flare
#

The cinematic variable change everytime. When the game loads, it isn't set. It's the job of my save loader to set it.

gray mural
#

if you set it somewhere - it gonna be changed afterall

#

it doesn't make sense

bold flare
#

Probably due to my bad english, sorry..

#

Ok, let me explain better..

gray mural
#

oh.

#

I have sent you friend request by mistake

bold flare
#

np

gray mural
#

was just looking on your profile

#

don't mention, just decline

#

ping me when you finish explaining

bold flare
# gray mural ping me when you finish explaining

I have an Animal with my Cinematic_e1c1 script attached.
On a pickable object, I have a DialogueTrigger script that will start a dialogue and the cinematic when the object is picked up. So here, I've set the "Cinematic" manually, like on the screen below.

On game quit, I need to save all the dialogue informations, to start it again on game load.
In order to achieve that, I get the "Cinematic" variable, and I set it in my save file. Then, on save load, I need to get it and set it back on the "Cinematic" variable of my dialogue.

I think that's better for everyone to understand the situation...

#

I don't know why I didn't give all those informations before ๐Ÿ˜…

gray mural
#
Cinematic savedCinametic;
bold flare
#

To save it, there is not problem. The thing is to get it back from the Animal gameobject, which is disabled on game load.

bold flare
gray mural
#

it's not disabled in some period of time I guess

bold flare
#

When the game starts (at the very beginning), this GO is disabled. It got activated just before the cinematic begins. When the game closes and open back, the game is like if it was never played, and I have to activate it back to start the cinematic again.

gray mural
#

there is a method to find it even if it's inactive anyway

bold flare
gray mural
bold flare
gray mural
#

or "name"

bold flare
bold flare
gray mural
#

just try not to do this method in Update

#
Cinematic[] objects = GameObject.FindObjectsOfType<Cinematic>();
#

you need to find objects of type Cinematic first

#

then you can use any kind of loop

#

I prefer using LINQ's First()

bold flare
gray mural
#
cinematicObject = objects.First(w => w.gameObject.name == "Blabla");
bold flare
#

๐Ÿค”

gray mural
#
using System.Linq;
#

you know this I hope ??

bold flare
#

So, this is supposed to work with unactivated objects

bold flare
gray mural
#
Cinematic[] objects = GameObject.FindObjectsOfType<Cinematic>(includeInactive: true);
bold flare
#

Oooh-

#

Ok

#

Let me check the doc

gray mural
# bold flare Ok

you just do it in 1 line

cinematicObject = GameObject.FindObjectsOfType<Cinematic>(includeInactive: true)
    .First(w => w.gameObject.name == "Blabla");
bold flare
#

Yep

#

I understand perfectly.
Thank you a lot for you patience and time!

gray mural
bold flare
#

Alright!

#

So I just need to convert my "Cinematic_e1c1" (deriving from Cinematic) to the Cinematic_e1c1 Type.
Perfect, thank you again!

bold flare
#

It's working!

gray mural
#

I have just mentioned

#

why can't you set it via [SerializeField] ?

#

there shouldn't be any issues here

#

oh, wait

#

no.

bold flare
gray mural
#

I am asking if you can set it via [SerializeField]

#

or am I missing something?

#

those are not the same objects

#

you have gameObject with Cinematic class in your scene

#

you just drag it into [SerializeField] property

bold flare
gray mural
#

that's the same like with FindObjectsOfType

#

but serializing them is better for your performance, @bold flare

rose stream
#

ok my question is simple
Can we use static libraries in Unity?

bold flare
#

(sorry, had to go)

#

So, I should have a property on my "LoadingManager" (or somewhere else) containing all the cinematics in an array, right?

gray mural
#

that's just array of Cinematic classses that you set in Inspector

#

isn't that you need

#

if you don't want to set them manually - you can also get their parent and extract children

bold flare
#

I could, that's just that I wasn't wanting to add a hundred of cinematics manually. But now that you're talking about this solution, it's true that it can be better for performance to have them here.

gray mural
#

and you should have mentioned that earlier

bold flare
#

Didn't I?

gray mural
bold flare
#

Oops-
My apologizes

#

Thank you again for your precious help!! ๐Ÿ™๐Ÿฝ

#

I think I'll try to do the array so!

gray mural
haughty pagoda
#

Are there any websites that are like archives or libraries for different algorithms, I want to learn data structures and algorithms but I donโ€™t do well with structured courses, itโ€™s better for me to hop around here and there

cobalt gyro
#

How do i check if an entire array has something

fleet furnace
buoyant crane
fervent furnace
#

youtube

fleet furnace
fervent furnace
#

leetcode contains lots of edge cases
though you can see the test case you cant pass

haughty pagoda
#

Thanks!!!

#

Is it timed?

#

It would be nice to research the algorithm as I receive the problem

fervent furnace
#

time limit for c and cpp is 2000ms i guess
i havent tried other language yet

fleet furnace
#

Its not timed but it does not give you the data structed that should be used to solve a particular problem
So you have to be able to google or know them before hand.

wind palm
# rare plank .

Your question doesn't make too much sense, do you have a visual to better understand?

rare plank
#

errrr

#

yeah one sec let me make something in paint

rare plank
#

10/10 art skills if i do say so myself

wind palm
#

Ah I see. I'm not overly familiar with GUILayout so perhaps you will need to wait for someone else.

#

If you're doing inspector related UIs I'd recommend the UI toolkit however.

late lion
rare plank
#

ok will try

late lion
#

Red being the parent

potent sleet
late lion
rare plank
#

ah my bad

potent sleet
rare plank
#
        public async void OnGUI()
        {
            GUIStyle areaStyle = new(GUI.skin.box);
            areaStyle.fixedWidth = 300;
            areaStyle.normal.background = AutoDonateGlobals.blackTexture;

            if (showUI)
            {
                // Parent area
                GUILayout.BeginVertical();

                GUILayout.BeginVertical($"AutoDonate v{AutoDonateGlobals.pluginVersion} - by architelos", areaStyle);
                GUILayout.Space(20);

                GUILayout.Label("Accounts");
                bool selectAccount = GUILayout.Button("Select Account");
                bool saveAccount = GUILayout.Button("Save Account");

                if (saveAccount)
                {
                    GUILayout.BeginVertical("Enter Credentials", areaStyle);
                    GUILayout.Space(20);

                    inputEmail = GUILayout.TextField(inputEmail);
                    inputPassword = GUILayout.TextField(inputPassword);

                    bool saveCreds = GUILayout.Button("Save");

                    if (saveCreds)
                    {
                        await AutoDonateHelpers.SaveCredentials(inputEmail, inputPassword);
                    }

                    GUILayout.EndVertical();
                }

                GUILayout.EndVertical();

                GUILayout.EndVertical();
            }
        }
late lion
rare plank
#

oh oh bruh

rare plank
# late lion You're still nesting the two groups inside each other.

so something like this? sorry i dont really get what you mean

            GUIStyle areaStyle = new(GUI.skin.box);
            areaStyle.fixedWidth = 300;
            areaStyle.normal.background = AutoDonateGlobals.blackTexture;

            if (showUI)
            {
                // Parent area
                GUILayout.BeginVertical();

                GUILayout.BeginVertical($"AutoDonate v{AutoDonateGlobals.pluginVersion} - by architelos", areaStyle);
                GUILayout.Space(20);

                GUILayout.Label("Accounts");
                bool selectAccount = GUILayout.Button("Select Account");
                bool saveAccount = GUILayout.Button("Save Account");

                GUILayout.EndVertical();

                if (saveAccount)
                {
                    GUILayout.BeginVertical("Enter Credentials", areaStyle);
                    GUILayout.Space(20);

                    inputEmail = GUILayout.TextField(inputEmail);
                    inputPassword = GUILayout.TextField(inputPassword);

                    bool saveCreds = GUILayout.Button("Save");

                    if (saveCreds)
                    {
                        await AutoDonateHelpers.SaveCredentials(inputEmail, inputPassword);
                    }

                    GUILayout.EndVertical();
                }

                GUILayout.EndVertical();
#

it still has the same issue, by the way

late lion
rare plank
#

hm okay, let me try moving it

dim gust
#

hey, for example i have 3 game object slots in the editor, how do i make that i can colapse them in the editor

heady iris
#

you could make a struct that holds several game objects

#

you'll be able to fold that

#

otherwise, you'd need to write a custom editor

brittle nebula
#

How does AddForceAtPosition work? I know what it does but I mean internally, the physics behind it.

fervent furnace
#

i think you can google rolling motion

#

i completely forgot the physics studied in university

vast patio
#

Is it possible to add a function to this GameManager.OnGameStart Action event, where I put in parameters, without adding argument to the OnGameStart event.
I dont wanna write a function for every menu to hide.

ashen yoke
#

yes

#

() => { ... }

#

this creates a closure

#

closure captures variables

vast patio
ashen yoke
#

you write the way i posted it replacing ... with what you had after +=

vast patio
#

ahh

ashen yoke
#

dont forget ;

vast patio
eager fulcrum
#

Hey, I'm getting these zenject errors

#

any ideas what to do with them?

copper rose
#

are you using zenject instead of addressables? and why? ๐Ÿ˜„

eager fulcrum
#

addressables can't do things that zenject can

late lion
# eager fulcrum any ideas what to do with them?

It seems that something depends on PredictCombat, but PredictCombat also depends on that something, creating a circular dependency. It might not be a direct dependency. It could be indirectly through another type.

eager fulcrum
#

thats weird, I can't find anything

#

its not a direct dependency for sure

#

there's just one thing that references PredictCombat

late lion
#

What dependencies does PredictCombat have?

eager fulcrum
late lion
#

Does the error not include more information about where this circular dependency is, if you click it to see the rest of it?

eager fulcrum
#

i'll send u the whole error

#

one sec

late lion
#

Okay, something about the SignalBus and BattleUnit. I haven't used SignalBus, so I'm not sure if that can cause this kind of problem.

#

It seems like you're firing a signal as a BattleUnit is being initialized, which is maybe causing some problems because PredictCombat also depends on SignalBus, but hasn't been created yet. I don't know.

eager fulcrum
#

i'll check if thats a problem later

simple egret
#

The "object graph" in the error is weird though, there's only one item, which makes me think that PredictCombat has a field of type PredictCombat, so it just recurses indefinitely down

late lion
#

Might be a separate issue misidentified as a circular dependency.

eager fulcrum
#

^ thats the whole code

flint needle
#

how can i call a SaveAsset function before exiting playmode?

#

i try to have a callback to EditorApplication.playModeStateChanged but by that time the instance of the object i want to save is dead

dim gust
#

how can i make this character rotate with the camera

#

like in thrd person, i use a cinemachine camera

limber agate
#

Look it up first

#

Before asking

soft shard
# flint needle i try to have a callback to EditorApplication.playModeStateChanged but by that t...

If this is for the Editor, why not make a button to save in maybe a custom editor window or component context menu, or the top navigation bar, then you can manually click it before exiting play mode - but why might you need to save an asset at runtime anyway? Could you not make it a prefab and "override" the changes you want to keep? (which shouldnt matter if its at runtime or edit time AFAIK)

flint needle
#

because i have quit without saving, just cant help it sometimes ๐Ÿ˜…

#

and i do on runtime cause my tool is on runtime

dim gust
soft shard
# flint needle because i have quit without saving, just cant help it sometimes ๐Ÿ˜…

Fair enough, I would imagine because the play button is pretty much your only reliable way of stopping code execution, it probably cant be "paused" for other code to execute (though maybe theres some API I dont know about that does it), alternatively, maybe you could make a second prefab "clone" when you enter play mode, and just constantly save any changes you make, when you exit play mode, you can then update your main prefab with the clone, or just keep the clone - another alternative would be to create your own "exit play mode" UI button that calls the editors exit play mode, then you can make a "do you want to quit" prompt, but that would mean youd have to break the habit of pressing the exit button which is easier said than done for sure lol

soft shard
limber agate
dim gust
#

READ THE QUESTION DUDE

#

I need an object to rotate to the direciton the camera is looking, in third person

#

every single video is about MOVEING the player twords the retation

simple egret
#

object.forward = cam.forward - here you go

rugged storm
#

yo question, does flooring a negative decimal = 0??

limber agate
dim gust
limber agate
#

It literally isnt

dim gust
#

oh no, anyways

dim gust
simple egret
#

No?

soft shard
simple egret
# simple egret No?

That copies which direction it's looking in, so its rotation by definition

rugged storm
#

i meant a negative decimal between -1 and 0 btw

rugged storm
simple egret
#

Flooring rounds down, it would be -1 if you had -0.1 for example

rugged storm
#

I think the issue was that i was dividing 2 ints

flint needle
simple egret
#

(rounding up)

rugged storm
#

oh god I do that alot in this code I just realized... cuz I use a reference to an constant that's an int and now i gata fix all of that

dim gust
#

the second is the result

simple egret
#

Looks good to me, it copies the whole camera's rotation

rugged storm
#

Debug.Log($"{new Vector2Int(Mathf.FloorToInt(pos.x / MapChunk.chunkSize), Mathf.FloorToInt(pos.y / MapChunk.chunkSize))}");
in a situation like this would simply casting one of the numbers in each division to flaot fix it?

simple egret
#

If you need it flat, then you should set the vector's Y to 0 in between

dim gust
simple egret
dim gust
#

thanks

swift falcon
#

Is there a way to simplify this code?

Vector2 GetVec()
{
    Vector2? dir = ...

    if (dir != null)
        return (Vector2)dir;

    return Vector2.zero;
}```
swift falcon
#

And made it Vector2 since might be clearer than generics

leaden ice
#

I recommend using the TryGet pattern instead of either of the paradigms in this code example (nullable value types, magic values (Vector2.zero) to indicate a missing value)

#

There's not really any way to simplify that snippet, no

#

it's quite simple already, no?

narrow spruce
#

why is my code not working

leaden ice
#

@narrow spruce don't crosspost

#

especially if you're not formatting your code

steady moat
# swift falcon Is there a way to simplify this code? ```cs Vector2 GetVec() { Vector2? dir ...

You can use https://learn.microsoft.com/en-us/dotnet/api/system.nullable-1.getvalueordefault?view=net-7.0 or ternary operator https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator or null-coalescing operator https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator

Vector2 GetVec()
{
    Vector2? dir = ...
    return dir.GetValueOrDefault();
}
Vector2 GetVec()
{
    Vector2? dir = ...
    return dir != null ? dir.Value ? Vector2.zero;
}
Vector2 GetVec()
{
    Vector2? dir = ...
    return dir ?? Vector2.zero;
}
swift falcon
#

First thing that pops into my head is you have a bool on each hex for _checking
Set it to true and then check all surrounding hexes
If it finds a white one then repeat it with that tile and it also sets itself as _checking

If a tile is completely surrounded by red or _checking tiles then set itself to red
Then work backwards through the tiles until you are back at the first

leaden ice
#

You should do a BFS or DFS (basically either as a flood fill) from each white tile to create a list of islands (skip any that you already placed in an island)

#

pick the biggest island

#

then turn every other white hex in every other island that is not the biggest and turn them red

#

You're doing a grid based game without knowing DFS/BFS?

#

You are going to feel pain

swift falcon
#

Breadth/depth first search

leaden ice
#

Breadth-First-Search and Depth-First-Search

wraith nebula
#

hi

#

i have an issue with a script

#

the fastikfabric

#

script

#

when it connects to my rig,

#

it anchors every part of the rig to the ground

#

of my map

swift falcon
#

For this code (That's not mine):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SD.Tools.Algorithmia.UtilityClasses;
using System.Collections;
using System.Runtime.Serialization;

    [Serializable]
    public class MultiValueDictionary<TKey, TValue> : Dictionary<TKey, HashSet<TValue>>
...```

These using directives are greyed out in my IDE:
```cs
using System.Linq;
using System.Text;
using System.Collections;```

I'm guessing they are still important because of possible types for the generics?
Let me know if I can remove them
leaden ice
#

psuedocode for what I said before:

islands = empty list
foreach (hex in tiles) {
  if (hex is red) skip
  if (hex is already visited) skip
  island = DFS(hex) // have DFS return all the visited/connected white hexes. It should also mark tiles it visits as visited so we don't waste our time on them later
  islands.Add(island) // dd this island to the list of islands
}

// now find the biggest island:
biggestIsland = FindLargest(islands)
// go through the rest and make them red
foreach (island in islands) {
  if (island is biggestIsland) skip
  foreach (hex in island) hex.color = red;
}```
leaden ice
swift falcon
#

Awesome thanks, don't know why there's so much useless fluff in this code

leaden ice
#

The IDE greys out things that are not in use

#

probably just sloppiness / not cleaning up on the dev's part

swift falcon
#

Anyone got any idea why this custom editor script does not recognize another class?
No namespaces are being used

This is purely in VS though, works perfectly within Unity itself

#

Also another related weird thing
When I use this script it works perfectly as I want it to but I still get an error log on this line:

mb.SendMessage(settings.methodName, settings.methodParameter);```
```Assertion failed on expression: 'ShouldRunBehaviour()'```
swift falcon
regal oak
#

If Animator shows the boolians work properly, but the inspector isn't showing them working, and in reality the boolians don't work. what does it mean?

heady iris
#

what do you mean the inspector isn't showing them working?

#

i don't believe you can view animator parameters from the inspector...

analog echo
#

Is there smth I'm missing?

I want to search for every document inside of 'mails' but this is not finding any document (using Firestore Database)

Example of a Document Path I have:
/mails/DBLG58-RFAJFA-6BFNDT

Code:

CollectionReference mailsRef = db.Collection("mails");
await mailsRef.GetSnapshotAsync().ContinueWithOnMainThread(task =>
{
        QuerySnapshot mailsQuerySnapshot = task.Result;
        Debug.Log(mailsQuerySnapshot.Documents);
        foreach (DocumentSnapshot documentSnapshot in mailsQuerySnapshot.Documents)
        { 
            Debug.Log(String.Format("Document data for {0} document:", documentSnapshot.Id));
            Dictionary<string, object> mail = documentSnapshot.ToDictionary();
            foreach (KeyValuePair<string, object> pair in mail)
            {
                Debug.Log(String.Format("{0}: {1}", pair.Key, pair.Value));
            }
        });
}

This debug logs [ ] and not any of the documents
Debug.Log(mailsQuerySnapshot.Documents);

Log: Firebase.Firestore.DocumentSnapshot[]

knotty sun
#

yes, because Documents is an object and so the ToString of that is it's type

analog echo
#

do you mean this line?
Debug.Log(String.Format("Document data for {0} document:", documentSnapshot.Id));

knotty sun
#

no, the line you showed above

#

as your object is an array maybe add .Length to the Debug so see thr number of entries

analog echo
#

I tried with Count and got 0

knotty sun
#

Count will not work with an Array

analog echo
knotty sun
#

Debug.Log(mailsQuerySnapshot.Documents.Length);

analog echo
#

it changes to Count

knotty sun
#

This Firebase.Firestore.DocumentSnapshot[] says its an Array. Arrays have a .Length property

analog echo
#

when Im writing .length and press tab, it changes to Count

leaden ice
analog echo
knotty sun
lean sail
#

ive definitely used foreach on it before, but this wasnt in unity

spark flower
#
public class VisionCone : Trigger {

    [SerializeField] GameData data;
    [SerializeField] float range;
    Actor target;

    private void Update() {
        if (target != null) {
            Vector3 _pos = transform.position;
            Vector3 _tpos = target.transform.position;
            if ((_pos - _tpos).magnitude < range) {
                float _angle = Vector3.Angle(transform.forward, _tpos - _pos);
                if (_angle < 45) {
                    data.Alarm = true;
                }
            } else {
                target = null;
            }
        }
    }

    public override void Execute(Warrior _war) {
        target = _war;
    }
}```
any idea how to remove the Update? or atleast optimise it abit, its not vital, but its desirable
lean sail
spark flower
#

its just the trigger event is in the player

lean sail
#

so this isnt a monobehaviour ie Update() isnt called every frame?

spark flower
#

it is a mono

#

and its called every frame

lean sail
#

then thats not doing what i said

spark flower
#

basically updating alarm while we are in the vision cone

#

when we trigger a collision enter it runs the Trigger function, which makes it run the code in update,

lean sail
#

my suggestion was basically use a collider (isTrigger = true) instead of doing a distance check

spark flower
#

the range variable is basicly the radius of the sphere collider

#

collision exit?

lean sail
#

but u should be able to just use OnTriggerXXX then instead of update

spark flower
#

i mean it runs the Execute function

#

the ontriggerenter event is run in the player

#

which runs the Execute function

#

which enables the code in update

#

but we need to update alarm

lean sail
#

u should still be able to do this with OnTriggerStay() or OnTriggerEnter/Exit then instead, with another collider the size of range to see if the target is within the area.
Or maybe run just run a coroutine to keep going until its not in range

#

now i understand more of what this is doing, id probably just use a coroutine

spark flower
#
public class VisionCone : Trigger {

    [SerializeField] GameData data;
    [SerializeField] float range;
    Actor target;

    private void Update() {
        if (target != null) {
            if (Vector3.Angle(transform.forward, target.transform.position - transform.position) < 45) {
                data.Alarm = true;
            }
        }
    }

    public override void Execute(Warrior _war) {
        target = _war;
    }
    public override void ExecuteExit(Warrior _war) {
        target = null;
    }
}```
i guess this is the optimisation
#

is performing 1 Update better then 30?

#

assuming i will do a loop in that 1 update

#

to check for the angle

marble halo
#

So im trying to make my camera tilt slightly when i move left or right, but for some reason despite being lerped, it doesn't feel smooth

#
    void Update()
    {
        movementdir = pInput.actions["Movement"].ReadValue<Vector2>();
        currentinputvector = Vector2.SmoothDamp(currentinputvector, movementdir, ref smoothinputvelocity, smoothinputspeed); //smooths value
        ccam.m_Lens.Dutch = Mathf.Lerp(0, movementdir.x * rotationMax,1f); //applies movement to camera tilt
    }```
#

nvm

heady iris
#

the third lerp term was 1f, ye

quartz folio
dense estuary
#

I dont think i did this right: https://hastebin.com/share/ikevoqahol.csharp How can i get my code to shrink the player gameObject when i trigger the Finish tag.

quartz folio
#

Also you can't have an IEnumerator that doesn't yield, so that code won't compile.

#

Read the Coroutines usage at the bottom of that page once you understand how Lerp works

dense estuary
#

So, I don't know how to fix this. It is shrinking the player gameObject, but its doing it instantly. Here is my script: https://hastebin.com/share/hujocefivo.csharp

#

ignore the name of the coroutine, I didnt change the name yet.

tropic quartz
#

That's because while loops don't run once per frame. They run as fast as possible.
So you need to add your own pauses there to not make it run at crazy speeds.

dense estuary
#

how can i add pauses?

tropic quartz
#

yield return new WaitForSeconds(3); would wait for 3 seconds.
You can probably do some math to make it frame based if you want to. I've also heard that yield return null makes it wait a frame though It's not really meant for that, I don't think... so I dunno if using it for this would be a good idea.

quartz folio
#

The code already has yield return null in it.

tropic quartz
#

Oh wait, you are right.

dense estuary
quartz folio
#

That's used if you don't provide a duration, but you are providing one

#

Line 18 passes duration, which you declare privately on line 9 with the default 0 value.

dense estuary
quartz folio
#

Yes

dense estuary
thorny spindle
#

I'm getting an odd error

wind palm
#

Ok thanks for letting us know

glad mason
#

hi is there an area for people looking for other programmers for their project in this server?

tawny elkBOT
glad mason
#

just checking

void basalt
glad mason
swift falcon
#

I've noticed a bit of an issue where unity SO's don't like interfaces with the inspector and you can't use interfaces with editor scripts...

So I was wondering, all of my scripts inherit from a base class and I wonder in the custom editor if I can create groups depending on if the script has an interace in it?

#

So for instance my base is "WorldEntity" so thinking if I can handle all variations inside WorldEntity and then use the same Editor script for everything that derives from WorldEntity

So something like... if this is typeof(<interface>) {show properties}?

swift falcon
#

It took me a bit of time to figure this out but...

bool interfaceIExpires = _worldEntity is IExpires;```Seems to be working
dry jewel
#

Hi, this question is for a card game I'm working on. So I have a card prefab in my card collection and deckbuilding scene. It contains certain scripts which do not work outside of the collection scene. I also have a battlefield scene where you duel an opponent. In that scene, in the hand, the cards are supposed to have drag and drop functionality. The the drag and drop is also on the card prefab. If I start the collection scene with this drag and drop enabled, it registers an error because the canvases that it requires are not in the scene obviously.
What is the best option in you guys' opinion to solve this?
Some options I've thought of:

  • Different card prefabs for each scene with some overlapping features for the stuff a card always needs.
  • Scene checking flag that determines if the script should be on or off depending on the active scene.
  • Adding the scripts at runtime and potentially forgoing the start and awake methods for the cards.
  • Manager that enables/disables scripts at the start by checking the scene. Not sure how that interacts with the start and awake methods.

But I really don't know what the best option is so what would you guys suggest I do?

TL;DR I have a prefab with scripts that only work in certain scenes, so they throw errors in other scenes. Looking for suggestions on how to fix this.

gray mural
#

or not

#

actually you should do prefabs for 1 scene

#

thought if you need them to work in other scripts too - add some additional functionality

#

some ifs

#

also you have said that canvases that are required are not in the scene

#

why?

#

create them in the scene or instsntiate in Start

#

typing on phone is so bad.

dry jewel
#

Yeah tell me about it, I feel like an unwieldy giant on the phone

#

So the canvases aren't there because they belong to a different scene.

gray mural
#

You have said that your scripts work in certain scenes. Do you know the reason?

dry jewel
#

Yeah, that I made them to work in that scene. One is a collection/deckbuilder, so it has all the assets needed for those scripts, the other is a battlefield and has the assets that battlefield scripts require.

#

This also leads to some scrips referencing objects that don't exist in all scenes

#

Which is where the error messages stem from

#

But I'm not sure what the most robust way to implement a fix would be

gray mural
#

you need to fix them or create new

#

I cannot say more without further context

dry jewel
gray mural
dry jewel
#

I'm not sure what else I could say that would be relevant

#

Like I've explained why the errors happen, I'm just asking on like an architectural level, what's the best fix for a case where you have a prefab in two scenes but it does slightly different things in either scene

#

And those things it does depend on the contents of the scene

#

They both need display functionality to actually show the cards, but one does not need drag and drop or any of the object dependencies that come with it, and the other does. What would you need to see to be able to help me?

soft shard
# dry jewel They both need display functionality to actually show the cards, but one does no...

Maybe you could add the drag and drop functionality as an additional script or interface, both scenes can create the prefab, if it needs the drag/drop functionality, it can enable that script or call functions from the interface, or you could use 2 different prefabs and maybe inheritance to have "similar but slightly different" functionality, anoher approach could maybe be setting up a script to handle dependency injection if these 2 different scenes just need a reference to exist in the scene before trying to do logic on said reference, you can use the "Script Exection Order" to make sure that injector is the first script to fire

latent latch
#

I'd just disable the functionality and enable it when needed

#

keep the cards between scenes

gray mural
dry jewel
gray mural
#

Like:

if (SceneManager.GetActiveScene().name == "blabla")
{
    // do smth
}
#

forgot if

#

phone.

gray mural
#

actually you can just disable d&d script when scene is XY

#

other still does work

soft shard
# dry jewel Do you mean inheritance like prefab variants?

I may not have fully understood your case, but I meant inheritance as in something like

public class Card : Mono
{
//card stuff...
}

public class DragDropCard : Card
{
//drag drop stuff...
}

Though it sounds like having a "canDragDrop" bool or similar for Card or an extra script attached to the same object as Card that only handles drag drop events, may be a simpler approach

dry jewel
#

Right so the scripts are separate, they're just both on the same gameobject

#

Like there's one d&d script, and then some other scripts, what's the best way to disable them for a scene, is it just having a flag check in the script itself to disable it in like the start method or the awake method?

prime sinew
gray mural
#

that depends on your game actually

#

just make sure to disable it before it starts executing

#

there is some window in Unity to do it

soft shard
# dry jewel Like there's one d&d script, and then some other scripts, what's the best way to...

If the card has all these "other scripts" you could have it reference and use functions on the card, some manager that would spawn the prefab could use SceneManager events as friend suggested earlier and call the relevant function(s), for example:

public class Card : Mono
{
[SerializeField] ScriptA a;
[SerializeField] ScriptB b;
[SerializeField] ScriptC c;

public void DoTheThing()
{
a.enabled = false;
b.enabled = true;
//...
}

public void DoAnotherThing()
{
//...
}
}
soft shard
gray mural
#

There is a window where you can make scripts execute before other scripts

#

and milliseconds offset between them

#

I do not remember how it is called

#

somewhere in project or build settings probably

#

they can find it

#

somehow.

void basalt
#

script execution order

#

@gray mural@soft shard

soft shard
#

Ah, thats what you were referring to

lean sail
#

as in only used for ordering

void basalt
#

yeah, arbitrary

gray mural
dry jewel
soft shard
dry jewel
#

Yeah it doesn't need to be on the card itself, that's a good point

glossy granite
#

so increasing fixed time step seems to improve performance in a game , but at what cost?

thin aurora
#

I highly recommend you do not touch those settings

glossy granite
#

what exactly does?

thin aurora
tepid juniper
thin aurora
#

In short, you're basically making it so physics calculations and FixedUpdate() are performed less

#

So yes, it is a performance increase, because you're effectively breaking your game

glossy granite
#

I have just increased it from .02 to .05 saw a huge performance improvement and saw that enemies were going faster as the only tradeoff

#

which can be easily solved

#

ill try leaving it at .02 and see, maybe the game is not that smooth, even if it is still at 60fps

thin aurora
#

Yeah so like I said, this is not the way to increase performance

#

But have fun figuring that out yourself

#

If your game performs bad, then you fix the actual code, and not the internal logic or rhytm

glossy granite
#

yep I agree with you, there is not shortcuts ๐Ÿ˜

#

this is were I saw the tip

#

In this video, weโ€™ll go through key physics considerations to keep in mind when you're aiming for high performance while moving from a prototype to a more complex project.
โญPhysics Documentation https://on.unity.com/3sB5x1y
โญLearn more https://blog.unity.com/technology/optimize-your-mobile-game-performance-get-expert-tips-on-physics-ui-and-aud...

โ–ถ Play video
soft shard
glossy granite
#

it think my issue is that I spawning loads of colliders to create walls in planets. Making them basic colliders and static has helped with the calculations.
But another solution could be to activate the gameobjects only when the player is near them

drifting crest
#

I wanna render webcam texture on a plane but when I am doing it , it is showing black screen only I have vuforia package in this project , when I tried to do this in an empty project with same code it's working , SO is there a way I can do it in the first project?

opaque lodge
#

hey guys, i have this situation: i have built the project once, is there a way to not have to do a clean rebuild on the whole project when i only made small changes. just for better debugging purposes

latent latch
#

delete previous files and rebuild

#

oh to not?

#

if you're compiling il2cpp, it usually is much longer than mono for one, but you shouldn't have to recompile the whole project for making small changes usually

south violet
#

Hey, Im using CSVHelper.CSVWriter and I am writing a float to csv and for some reason sometimes this written float in csv has 12 decimal digits. How is that possible?

terse stag
#

Hihihi! I just started Unity and I can't figure out how to achieve this:
I want to have a generic way to store data persistently (saving and loading the game) that I could convert to and from json, with reusable keys such as HEALTH, which could be applied to any animal/plant/item, etc...
This led me to a Dictionary<Stat, double> (Stat is an enum) which is fine I could definitely serialize this, but what if I want to store an integer? That's still doable, but annoying... But! What if I want to store a string? What if I want to store another object? Or a class, perhaps a Buff Instance for an animal?
It'd also be nice if possible to have them accessible in the editor
Am I over-engineering this? I know JsonUtil can convert classes to json, but that has also been a pain as it almost Never actually takes any of my fields...
I've been coming across So many dead ends, with no perfect solution... If you have any suggestions, please do ping me!

#

Oh and I have Odin Inspector if that becomes relevant!
Thank you!

rain crater
#

Hey, how do I draw a box, that I can click on in scene view and call some event? This is for an editor script.

rain crater
#

That could work, but I was thinking more of a 3D box

#

well, cube, I think

verbal cliff
lean sail
# terse stag Hihihi! I just started Unity and I can't figure out how to achieve this: I want ...

You can have some interface to denote things are Saveable. Each class u wish to save data from just implements this interface.
One method can just return object, each class returns whatever they want then. And since its class specific, when you load the data, you already know what the type is.
A SaveManager (or whatever you call it) would take the object returned from the method and just directly save to json

rain crater
verbal cliff
rain crater
#

Alright, thanks

rain crater
#

Okay, i've found a thing like Handles.CubeHandleCap, and it seems like it might be what I need, but now here's the question, how do I draw Handles.Button for X objects at once?

rain crater
#

Ok, but then how can I attach a function to that button? Normally I do it by putting the button inside an if, but if I do foreach and then if, it doesn't work

stark sinew
rain crater
#

Like, the buttons don't show up in the scene view

gray mural
stark sinew
stark sinew
gray mural
rain crater
#

this is a part of code that I have

foreach (PathPoint _pp in nodeObjects)
{
    if (Vector3.Distance(_script.points[0].GetGlobalPos('p'), _pp.GetGlobalPos('p')) < 25f)
    {
        Debug.Log("Kurde mol");
        if (Handles.Button(_pp.GetGlobalPos('p'), Quaternion.identity, 10f, 8f, Handles.CubeHandleCap))
        {
            _script.AddPoint(_pp);
            isAddingPoint = false;
            break;
        }
    }
}
stark sinew
rain crater
stark sinew
rain crater
#

it seems like removing the if(distance) helped

#

but that's weird, because my very specific debug message was being called thonk

#

ok, and now when I've made one if with two conditions, it works

stark sinew
#

If you just iterate over your path points and draw a button for each, without any other conditions, does it work as it should?

rain crater
#

yeah, as I wrote. Even if I put the distance condition in the same if as the Handles.Button, it also works as it should

#

Weird but ok, I can work with that

#

Thanks for help! ๐Ÿ˜„

stark sinew
#

Also, may I ask what exactly you're trying to achieve? Every path point has to be 25 units away from _script.points[0] but theoretically the path points themselves could all sit in one place?

#

You're welcome, glad you got it solved for now!

gray mural
#

Does anyone know what method in Unity's TMP_Text or TextMeshProUGUI classes wraps the last word on the next line, when line's width exceeds max width, or returns it on the previous line when character is deleted?

#

I really cannot find it.

#

But I need to find it.

#

I need to see when last word is wrapped and transfer this word into other TMP_Text, not next line

rain crater
#

They can all sit in one place, but that would be weird, since that would mean a path with 0 distance

amber depot
#

hi guys, I have a small question and a problem lets say like that

main zenith
#

Hi there, could anyone perhaps please help me out with the Furioos SDK if anyone is perhaps familiar with that? We're trying to upload an HDRP project as a render streamed execution but we want to be able to call functions on the browser from Unity and vice versa using both the Unity SDK and JS SDK. We've attempted using the interactions with browser scripting which is a webgl method, but just for testing and that did not seem to work. How can we go about calling these desired functions in this way?

amber depot
#

so I have a GameManager, where I am unsing the Singleton pattern and I am calling a Variable of type GameObject from this script to a script which is attached on my main Camera GameObject, but the instance is always empty when called in the script which are attached to the Main Camera GameObject. I am using VS as my IDE and using breakpoints I came to know that the scripts attached to the Main Camera GameObjects are always called first that any other in the Scene. So is it true for all and is default in Unity or is it just the way the Project is setup

leaden ice
amber depot
#

mm ok the I am going to set my instance to my singleton value in Awake

#

and see what happens

leaden ice
amber depot
#

Thanks

golden flume
#

Hey, i would like to make an damage zone like in battle royal game. I have try with a sprite and reduce his scale, but the probleme is i can't make it random. In 2D.
Do u have idea how to proceed ?
Because with a sprite who is reduce over time, player will know where is the center of the safe zone

jaunty needle
#

Hello guys

#

So I'm trying to make a level loading system much like Undertale's

#

Wher eyou have differnt rooms and there is a transition between them

#

Now I wonder which is the best approach, to have multiple tiny scenes and load between them, or one giant scene and do scene transitions between areas, or a combination of both

#

Because if I had a scene for every room the number of rooms would be gigantic

mossy shard
#

for the different sections

#

when in like snowdins , the houses should be in the main scene

#

with the transitions

#

in bigger places, another scene

jaunty needle
tropic quartz
jaunty needle
#

Ah so separate scenes alrighty

tropic quartz
#

What mihnwq probably meant is that in a lot of RPGs it'd probably be more optimal to have shops etc. as just a part of the same scene.
Door could be a teleport and the shop's insides could just be off the map in the void.
That way the game doesn't need to constantly unload/load stuff.

But I wouldn't overthink that stuff if it's a little solo project.

jaunty needle
#

oooh

#

I didn't think bout the teleport thing

vivid wind
# jaunty needle Ah so separate scenes alrighty

It depends on your needs, keep in mind, that by default all loaded data in a scene is unloaded during scene change. So You'll need to be marking stuff as DoNotDestroy or reloading it on scene load. So that should be a consideration when deciding between doing a one large scene or multiple scenes.

jaunty needle
#

Yep yep

uneven monolith
#

Hey! quick question; if i have

Vector2 forward```
and i want to instantiate object facing to that direction, can i just use the forward vector as Quoternion or what kind of maths i have to do(i hope not very complicated ones lol)
#

ps. i have no idea how quoternions work so googling was ewwhhh

tropic quartz
#

Vector2? Is this a 2D game?

uneven monolith
#

ye

#

and it doesnt matter that much if it goes 90/180 degrees to wrong direction or another, i can deal with that kind of stuff myself, just like so it orientates depending on the vector2

#

actually google helped me already with right words

#

atleast i hope that works

tropic quartz
#

I'm not entirely sure what your Vector2 forward is, but there's Transform.LookAt that makes an object face a target.
If that Vector2 is already the correct rotation then you could just set it's values directly to the transform, though.

heady iris
#

yes, you can produce a rotation (a Quaternion) from a vector using LookRotation

#

Note that LookRotation defaults to using Vector3.up as the "up" direction. This could cause some weird rolling if you also happen to put in Vector3.up (or Vector2.up)

#

I suppose you should use Vector3.forward as the "up" direction to keep it consistent

#

the titular use of Quaternion.LookRotation is to...get a look rotation

#

in that case, you want the camera to be upright

#

no roll around the local Z axis

wise escarp
#

Hi, I'm using Mathf.Abs(0 - transform.rotation.z) to get a value between 0-1 between 0-180 degrees rotation
At 90 degrees rotation, the middling value is 0.7 instead of 0.5, despite 0 degrees returning 0 and 180 degrees returning 1. I'm sure I'm misunderstanding something here, how do I get this more exact?

knotty sun
#

rotation is a quaternion not a euler value

mossy shard
#

it is better to change the forward direction of the object to the target by calculating the diff of the positions

atomic iris
#

hi im having an issue where im creating and assigning a render texture to a raw image via script. I turn that render texture into an asset in the project as well. when i enter play mode for the first time it works fine, but after exiting the texture for the raw image gets set to none. This isnt an issue if i manually assign the asset from the project window to the raw image but im trying to automate that process a bit and im wondering why the raw image is getting reset

wise escarp
cold egret
#

- I'm working with localization and stumbled upon custom startup locale selector. Although other than an ability to create one by implementing an interface, i didn't find any information. My implementation is going to have some non-static dependencies, and i need to make sure it makes its way there before its called by unity. Is this possible?

brittle nebula
#

I am trying to use unity netcode, but whever a client joins the rigidbody physics just completelly breaks and he just starts to glitch fly around. I don't even have any code which controls the rigidbody its just the rb itself seamingly broken? It works all fine for the one who hosts it, but for the client it breaks the, also the only thing it has is a collider and rb and a network object component.

prime sinew
gray mural
woven dome
#

Hi there
Does anyone know the reason why this would both print out false?

Pose left = default;
Pose right = default;
Debug.Log ( left == right );
Debug.Log ( left.Equals( right) );
cold egret
#

- Is pose a struct?

knotty sun
#

because left and right are 2 different objects

gray mural
woven dome
woven dome
knotty sun
#

but == and .Equals does noty compare contained values unless you program it

woven dome
knotty sun
gray mural
woven dome
knotty sun
gray mural
#

you need to compare struct values

#

by overriding bool Equals

woven dome
#

that's what == does internally

gray mural
#

as you see.

woven dome
knotty sun
#

.Equals and == are c# not Unity

gray mural
#

for classes for sure

#

for struct I guess too

woven dome
knotty sun
#

now you say that

gray mural
#

@woven dome that's how you override "==" and "!=" of struct

private struct Nice
{
    private int foo;
    private float bar;

    public static bool operator ==(Nice left, Nice right) =>
        left.foo == right.foo && left.bar == right.bar;

    public static bool operator !=(Nice left, Nice right) =>
        !(left == right);
}
woven dome
gray mural
#

and yeah, that works for struct

#

I was not sure

knotty sun
#

docs for Pose say == is overriden so (left == right) should be true

gray mural
#

just the same like with class

gray mural
#

do it the same like with a struct

#
private class Nice
{
    private int foo;
    private float bar;

    public static bool operator ==(Nice left, Nice right) =>
        left.foo == right.foo && left.bar == right.bar;

    public static bool operator !=(Nice left, Nice right) =>
        !(left == right);
}
woven dome
gray mural
knotty sun
#

you should probable use Pose.identity instead of default

woven dome
woven dome
knotty sun
#

thats why there are docs

gray mural
#

it doesn't though

#

that's strange

#

@woven dome can you try to convert default to Pose

#
Pose left = (default)Pose;
#

idk if that helps

tropic quartz
#

Just for my curiosity I tried declaring just 1 pose, setting it to default, then asking it if "somePose == somePose (yes, the same var twice) and it says "false". sadok

knotty sun
#

i wonder if that is because Pose contains a Quaternion and a default Quaternion is not a valid one

gray mural
#

If some fields are null - comparing those fields will result in null

tropic quartz
#

Ooh!

gray mural
#

Quaternion.identity does not contain null

knotty sun
#

there cannot be any nulls in Pose

gray mural
#

so it returns true

gray mural
knotty sun
#

where?

gray mural
#

@tropic quartz you can try debugging it

knotty sun
#

it's 4 Vectors and a Quat

gray mural
#

there should be

knotty sun
#

obviously not

gray mural
tropic quartz
knotty sun
#

yes, as I said, default Quaternion is not a valid quaternion

gray mural
#

or it is?

#

can you debug it?

knotty sun
#

Quat is a struct it can never be null

gray mural
#

no, it is

knotty sun
#

yes it is

gray mural
#

I think

gray mural
knotty sun
#

so Pose can never contain any value that is null

gray mural
tropic quartz
#

Yeah in case there was confusion I didn't use .identity. That's var is just Pose somePose

knotty sun
#

i agree, logically default Pose == default Pose. The fact it is not means that the == override is checking for something

tropic quartz
knotty sun
gray mural
knotty sun
#

qed

gray mural
#

because everything is 0

knotty sun
#

no everything is not 0. everything is 0 if you use default

gray mural
knotty sun
#

and a Quat with a 0 w is invalid

gray mural
#

w is certain for every xyz

knotty sun
#

indeed, so in the case of Pose it is passing the == check to the == of Vector3 and Quaternion and, probably the Quaternion == is returning false

tropic quartz
#

I was confused about identity but it's actually static so no wonder I couldn't reference it the usual way.

gray mural
knotty sun
#

we know that w=0 in a Quat is not allowed, what I am saying is if the == operator of Quat is checking for this it could be returning false because it would be an invalid Quat

tropic quartz
#

Anyway putting Pose.identity spits out this:

gray mural
#

you have said it already and I haven't thought about it

#

that's strange that it doesn't throw any errors

knotty sun
#

which would make default Pose false as well

gray mural
knotty sun
#

easy check
Quaternion q = default;
Debug.Log(q == q);

#

we know Vector3.zero is perfectly valid so it can only be the Quat causing the confusion

tropic quartz
#

Yeah that q is false in Debug.Log

#

I tried

knotty sun
gray mural
#

though we should have checked them both

tropic quartz
#

Well as a newbcake, I learned something new, heh.

gray mural
knotty sun
#

tbh, I had not expected this behaviour either but it was the only thing that made sense

gray mural
knotty sun
#

well that and I dont make a habit of having invalid Quats in my data

#

there is a reason why Quaternion and Pose have a .identity static property, it's not just for show

gray mural
#

Vector3 also does have Vector3.zero

#

though you can set it as Vector3 vector = default;

#

so it doesn't make so much sense if I don't miss something

knotty sun
#

so Vector3.zero == default Vector3
but Quaternion.identity != default Quaternion

gray mural
#

and we all use it, not default

#

I guess we all do

knotty sun
#

I guess 99% of Unity users does not even know that default exists

gray mural
leaden ice
#

Sometimes there's readability/code maintainability advantages to defining something like Vector3.zero even if a language feature can technically get you the same thing

gray mural
knotty sun
#

need to be careful with default because of differing behaviour between structs/primitives and classes

#

better to have an explicit .zero

inland crescent
#

I'm trying to get my player to move in the same direction of the camera, I have mouse look and player controller

inland crescent
gray mural
#

I am sorry if you have understood this from my previous message

#

just clarifying it

inland crescent
inland crescent
gray mural
#

can you explain better?

inland crescent
gray mural
leaden ice
inland crescent
gray mural
tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

gray mural
leaden ice
# gray mural !code

basically before you do controller.Move(move * ...); you have do to move = controller.transform.rotation * move;

#

to adjust the input for the actual direction it's facing

inland crescent
leaden ice
#

and yeah that looks like either notepad or vim without any line numbers

gray mural
leaden ice
inland crescent
# tawny elk

I'll keep that rule in mind, I'm still newish to the server

gray mural
#

Does anyone know how to clear TMP_Text's last line?

#

so I have:

dsjfds flkdsjfsfudso fisdufsd iuosnewrnrwejlskdfs
fsdoreuiw rewjls jfdsoufds ijlfw jrewjk rewljk w
ewroufdsjl kfsdjkfdsljk weoriur ewui rewfsdlaj fds
fdsajfdsfdsfsdasfd
#

I need to have:

dsjfds flkdsjfsfudso fisdufsd iuosnewrnrwejlskdfs
fsdoreuiw rewjls jfdsoufds ijlfw jrewjk rewljk w
ewroufdsjl kfsdjkfdsljk weoriur ewui rewfsdlaj fds
#

no Split(\n) โŒ