#archived-code-general

1 messages · Page 356 of 1

vale bridge
#

does GC handle the memory dealloccation I assume, well, there isn't really a way that I know of since C# uses Gc

late lion
sullen drift
#

I have a question. I have method that has an action parameter. Then inside the method, i subscribe the action with another method. Should i unsubscribe it? or just let it be since its a local variable action?

vale bridge
sullen drift
#
void Method (Action action) {
  action += OtherMethod
}

if i do this, i have to unsubscribe it?

vale bridge
#

I'm actually not sure if delegates are pass by reference

steady moat
vale bridge
thick terrace
#

yeah, that's only reassigning the local variable action

vale bridge
sullen drift
#

got it thanks

gray mural
#

What do you mean? Only a single drag should be registered, if I understand correctly? In this case, what about creating a boolean?

radiant marten
tardy beacon
#

why is there a SceneManagement in both of the UnityEditor and UnityEngine namespaces?

rose fulcrum
#

Is there any reason why Image.crossFadeAlpha would work to decrease alpha but not increase it?

#

public void FadeOut()
{
background.CrossFadeAlpha(0, fadeOutTime, true);
text.CrossFadeAlpha(0, fadeOutTime, true);
}
public void FadeIn()
{
Debug.Log("test");
background.CrossFadeAlpha(1, fadeInTime, true);
text.CrossFadeAlpha(1, fadeInTime, true);
}

leaden ice
rose fulcrum
rose fulcrum
leaden ice
#

see if and when the functions are called, and what fadeOutTime and fadeInTime are set to

#

the function itself works fine, so your usage of it is likely wrong somehow

rose fulcrum
#

they are hard coded atm to 1.0f and 0.4f respectively

leaden ice
#

define "hard coded"?

#

Use Debug.Log to make sure the value is actually as you expect at runtime

#

When debugging your code it's best to question all your assumptions.

rose fulcrum
#

Lemme see if the alpha values are changing via code tho

leaden ice
#

ok now add more logging to the actual functions. You don't even have a log for fadeout.

rose fulcrum
#

I can see it working lol

leaden ice
#

make sure your "test" thing is even printing. It'd be better ot have an informative label there though like Debug.Log($"FadeIn called for {background} and {text}");

leaden ice
#

Is your log printing or not

rose fulcrum
#

yes

leaden ice
#

Ok but like

#

we still want to log fadeout

#

because it can give us valuable clues

#

for example maybe your code is calling FadeOut accidentally right after FadeIn

#

and that's why it doesn't appear to work

#

When you debug things, you need to be thorough, you can't take shortcuts

#

if you are thorough, you are guaranteed to find the problem instead of bashing your head against the wall

#

and if you put the log and it's not doing that, then at least you eliminate that possibility.

#

It's about playing the game of deduction

rose fulcrum
#

Interestingly enough. pulling the alpha in the update loop only returns 1

leaden ice
#

there's all kinds of things that could be going wrong

#

you could be referencing the wrong object
you could have other code overwriting the alpha
you could have an animation overwriting it
etc

rose fulcrum
#

public void FadeIn()
{
Debug.Log($"fading in from {background.color.a} and {text.color.a}.");
background.CrossFadeAlpha(1f, fadeInTime, true);
text.CrossFadeAlpha(1f, fadeInTime, true);
Debug.Log($"Done fading {background.color.a} and {text.color.a}.");

}
#

Logs the same color.a before and after

leaden ice
#

crossfade takes time

#

it doesn't happen instantly

rose fulcrum
#

trrruuue

#

sec

leaden ice
#

it won't be done on the line after

#

what I'm more interested in seeing is the logs when whatever happens happens that is supposed to cause the fade in. And with FadeOut having logs in it as well

#

basically - please provide more context here if you want more useful help.

rose fulcrum
#

The thing with the fadeOut method, and why I'm not concerned with it.
I instantiate the gameObject I'm fading in and out from.
And after it fades out, its destoryed.

#

So its not like I'm ever fading back in from fading out

steel vortex
#

Hello, does anyone know a good tutorial to create FPS Charackter controller with animation assets included weapons, I have a Asset with some animations and want now to create the movement und etc

leaden ice
#

and then we don't have to worry about it anymore

mighty void
#

anyone knows or have experience making procedural 2d world?

leaden ice
#

It's hard to help when working blind

mighty void
#

i have a lot of troubles making biome system

rose fulcrum
#

You want me to show you the logs of it running once?

#

I guess I'm confused as to what;s being asked

leaden ice
#

I have no idea what we're even trying to do here

lean sail
leaden ice
#

I don't know anything about the project, or what these objects are, or when and why they are supposed to be fading in or out

#

or what script this code is on

#

or what code causes it to run and when

rose fulcrum
#

respetfully. Nevermind

mighty void
granite bone
#

How to Instantiate a prefab, not a clone. I want the blue link.

leaden ice
mighty void
mighty void
leaden ice
# mighty void

you don't "specify" where to put specific biomes. It's based on the noise function

#

that's kind of the point

#

this is for procedural generation

granite bone
#

thank you @mighty void

mighty void
#

and how to specify where put that biomes?

leaden ice
mighty void
leaden ice
eternal shoal
#

Hello! Am I right to assume that the Packages/package folder should not be included in VCS? It's 60mb heavy. I don't recall it being there before creating a Unity 6 project.

leaden ice
#

what do you have in there that is 60mb?

#

The most common reason to use an embedded package btw is if you made a manual change to a built in Unity package.

mighty void
eternal shoal
leaden ice
#

I've never seen it before

#

I would probably try excluding it from VCS, make a basic scene, clone the repo, and see if it works on the other side

eternal shoal
leaden ice
#

I would definitely exclude at least the ProjectData~ folder if not the entire "package" folder (keep Packages)

eternal shoal
eternal shoal
leaden ice
#

and we always exclude the Library folder

#

it's very confusing to me that it's showing up inside your Packages folder 🤔

eternal shoal
leaden ice
#

I do wonder if it's a Unity 6 bug or something

eternal shoal
#

It doesn't seem to get generated again. Not when restarting nor when pressing play.

leaden ice
#

any chance it got copied in there accidentally somehow?

#

If you make another new project do you see it again?

sturdy holly
#

has anyone ever had the unity editor fail to open any project at all. I have a guy and we set up him with unity- has a personal license. create a new project or try and open an existing and the editor will simply fail to open. tried running the hub with admin and all sorts but nothing

#

it wont even start up

eternal shoal
eternal shoal
#

The project is still generating and the folder is already there.

boreal glacier
#

So for enemies in encounters, would I be better off storing their stat values in scripts attached to their prefabs?

#

Or would it be better to have them all stored collectively in a script as a list

eager yacht
#

That package folder is from the project template in the hub (the provided ones have it), but it's not supposed to be sticking around as it pulls the stuff out of there to make your project LUL

eternal shoal
boreal glacier
#

I mean in active combat where should I store stats

boreal glacier
#

I cant just pull directly from the SO, because a fight could have 3 "soldier" units for instnace

#

and doing that would make them share hp

eternal shoal
eager yacht
#

Yeah, not sure why it's still there for you

eternal shoal
#

I would assume this is a Unity 6 preview bug. I've literally just installed Unity on this PC and created a project. I'd be surprised to have broken something somehow.

#

Thank you both for your help! I'll just delete it and be happy! card

boreal glacier
#

Im thinking I could maybe just have an "enemyStat" script applied to every enemy prefab, which uses its ID component to get its stats

eternal shoal
boreal glacier
#

Having the enemyStat script on startup take the enemyID from its own object and pulling the needed stats from the SO

#

I still need runtime stat updates for the sake of damage, status effects and other changes

hidden flicker
#

My looking around / movement feels very jittery. What might be the problem?

eager yacht
#

Is your camera a child of your rigidbody

#

(I'll just drop this here since I've had this saved in my bookmarks forever)

rose fulcrum
swift falcon
#

Hey can anyone help me, I'm not sure why but when I grapple I get launched into oblivion? I'm not sure why and I'm sure it's from this script, especially the getkeydown function part.

tawny elkBOT
hidden flicker
#

Did you remember to set the values in the inspector

hidden flicker
bronze crystal
#

i tried to create rotate around player ```using UnityEngine;
using Unity.Cinemachine;

public class CameraController : MonoBehaviour
{
public CinemachineFreeLook freeLookCamera;

void Update()
{
    if (Input.GetMouseButton(1)) // Right mouse button
    {
        // Enable camera rotation
        freeLookCamera.m_XAxis.m_MaxSpeed = 300;
        freeLookCamera.m_YAxis.m_MaxSpeed = 2;
    }
    else
    {
        // Disable camera rotation
        freeLookCamera.m_XAxis.m_MaxSpeed = 0;
        freeLookCamera.m_YAxis.m_MaxSpeed = 0;
    }
}

}

#

but this library deprecated

compact fog
#

So only sorta a code question. I was following a Unity folder structure video to get an idea of good practices and am running into a issue.

I have a ScriptableObject called ScriptableUnitBase snippet here:

public abstract class ScriptableUnitBase : ScriptableObject
{
    public Faction Faction;

    [SerializeField] private Stats _stats;
    public Stats BaseStats => _stats;

    // Used in game
    public FriendlyUnitBase Prefab;

    // Used in menus
    public string Description;
    public Sprite MenuSprite;
}```

Which is inherited by ScriptableFriendly which is the object i create in my project: `public class ScriptableFriendly : ScriptableUnitBase`

Now I am trying to assign my Player prefab object, which has a Player script to the scriptable object instance. 

Player inherits from FriendlyUnitBase: `public class Player : FriendlyUnitBase` which inherits from UnitBase `public abstract class FriendlyUnitBase : UnitBase`. 

The issue I am having is that the FriendlyUnitBase Prefab variable will NOT allow assignment of the Player object. I even tried setting the variable to take Player object, etc but nothing would allow me to assing a prefab to that variable. 

What I am i missing?
merry ibex
#

Is there a way to store strings outside of the globalmetadata.dat file?

#

I have a bunch of strings in which I need to keep secret as they contain links to game servers

#

Is there perhaps a package for this I can install?

bronze crystal
#

if someone could help me

swift falcon
#

i don't know it makes you fall through the floor still and like you don't swing around at all there's nothing keeping you up (pulling you up), like no centripetal force whatsoever

granite bone
#

Hey,
I wrote a script for my prefab.
Created 500 game object with different positions. (Clones)

How to link them back to blue link prefab? I have to more modifications and don't want to make.them manually for each

hidden flicker
naive swallow
#

If you spawned them in the editor, changing something on the prefab will apply to all instances of it as long as that field isn't already changed

granite bone
#

In runtime

#

That why I am asking how to link them back to blue

rigid island
restive ice
#

drawing arrows on a tilemap

wary coyote
#

    private void GenerateTwistedTorusWithoutNormalVector()
    {
        vertices = new Vector3[thetaDivisions * phiDivisions];
        rotations = new Vector3[thetaDivisions * phiDivisions];

        float minorRingTwistIncrement = _offsetAlignment.y;

        for (int i = 0; i < thetaDivisions; i++)
        {
            float phi = 2.0f * Mathf.PI * i / thetaDivisions;

            for (int j = 0; j < phiDivisions; j++)
            {
                float theta = 2.0f * Mathf.PI * j / phiDivisions;
                float majorRadiusTwist = _offsetAlignment.x * j / phiDivisions;

                float twistedTheta = theta + minorRingTwistIncrement;
                float x = (majorRadius + minorRadius * Mathf.Cos(twistedTheta)) * Mathf.Cos(phi + majorRadiusTwist);
                float y = (majorRadius + minorRadius * Mathf.Cos(twistedTheta)) * Mathf.Sin(phi + majorRadiusTwist);
                float z = minorRadius * Mathf.Sin(twistedTheta);

                Vector3 position = new Vector3(x, y, z);

                vertices[i * phiDivisions + j] = position;
                //rotations[i * phiDivisions + j] = GetLookVector(position, theta, phi); // fail code
            }
        }
    }```

How do I get a pointing vector that points from a position to a distation in this use case? I can't get a vector to just point from A to B correctly because I am struggling to comprehend my own torus math no matter how hard I try to simplify it.

I am not good at vectors, worse at rotations and directions and quaternions. I just want to say 'From any given point, give me the direction to point at your center'
#

The center of a given ring's minor radius

#

I can set all the positions correctly perfectly, but Ive failed for hours to correctly then point at their root

lean sail
wary coyote
#

I stopped trying to use quaternion.Anything because they are a black box of which I have no comprehension why its going wrong because I cannot get any debug info out of them

#

likewise when I say 'Vector3.foward' or whatever, that just causes more issues because what IS forward?

lean sail
#

Then you should share your issues with that. Doing your own trig imo is rarely needed. I've yet to use any trig function in my game

wary coyote
#

Sure, 1 sec I keep deleting the code that doesnt work

lean sail
wary coyote
#

Right sorry I didn't mean literally what is vector3 forward, you aren't understanding

#

Ill try to speak more clearly

#

I am asking in the insane exasperated way that 'vector3 forward', forward as a concept is meaningless without 3d space around it, what is 'forward' on any given point is equally meaningless

#

like in space there is no down

#

so when the net is like 'just point it forward'

#

it doesnt help

#

because nothing.forward has produced

hidden flicker
wary coyote
#

Anyways sorry the code, focusing on the code

#

I appreciate your patience in advance, I have been grinding mybones to bloody tears spending h ours making only backwards progress just trying to get to point from A to B

lean sail
wary coyote
#

Nevermind I see you're only interested in arguing about semantics with me :/

#

I really dont need this

#

I am trying to be helpful and civil, I don't appreciate the ongoing friction

vagrant blade
#

You can't say you're bad at vectors then say someone's simply arguing semantics. Forward us literally 0,0,1 in world space.

It will always point along the z global axis regardless of where you are.

wary coyote
#


    private void GenerateTwistedTorusWithoutNormalVector()
    {
        vertices = new Vector3[thetaDivisions * phiDivisions];
        rotations = new Vector3[thetaDivisions * phiDivisions];

        float minorRingTwistIncrement = _offsetAlignment.y;

        for (int i = 0; i < thetaDivisions; i++)
        {
            float phi = 2.0f * Mathf.PI * i / thetaDivisions;

            for (int j = 0; j < phiDivisions; j++)
            {
                float theta = 2.0f * Mathf.PI * j / phiDivisions;
                float majorRadiusTwist = _offsetAlignment.x * j / phiDivisions;

                float twistedTheta = theta + minorRingTwistIncrement;
                float x = (majorRadius + minorRadius * Mathf.Cos(twistedTheta)) * Mathf.Cos(phi + majorRadiusTwist);
                float y = (majorRadius + minorRadius * Mathf.Cos(twistedTheta)) * Mathf.Sin(phi + majorRadiusTwist);
                float z = minorRadius * Mathf.Sin(twistedTheta);

                Vector3 position = new Vector3(x, y, z);

                vertices[i * phiDivisions + j] = position;
                //rotations[i * phiDivisions + j] = GetLookVector(position, theta, phi); // fail code
            }
        }

        // Apply the calculated positions to clones
        for (int i = 0; i < clones.Length; i++)
        {
            clones[i].transform.localPosition = vertices[i];
        }
    }```

What I want from this code is to set every position's rotation to face towards the center of its minor radius centerpoint
the minor radius center point is the position on the major radius which the minor radius is arrayed around
#

I can say all of that in english words, nothing I type in code has achieved that result

solemn bridge
#

I've got an issue I don't quite understand and haven't seen before. I have a wheel that when I rotate using the rotation gizmo rotates correctly at it's center pivot point (the way a wheel should rotate) but when I rotate it using the X value of the rotation in editor (and code) it rotates along a pivot point that is completely different. Any ideas?

lean sail
cosmic rain
wary coyote
#

I'm not and I don't appreciate everyone dogpiling to attack me, I'm just going to leave because no one is interested in seeing my point of view, you'd all rather argue semantics than to help

#

Thank you for your time

vagrant blade
#

Nevermind, deleting the answer.

#

Good luck

solemn bridge
#

If I rotate with the gizmo tool it rotates on the axle

#

If i rotate with the x value of the transform is rotates along a pivot point to the left

solemn bridge
#

@cosmic rain Theres no code

#

That's the thing

cosmic rain
# solemn bridge

You have the gizmos in "center" mode. That would rotate the object around its center. While everything else would rotate it relative to it's pivot point. I guess that's the issue.

solemn bridge
#

I changed that same thing

cosmic rain
swift falcon
half cosmos
#

A vector from point a to b is just b - a

#

You can normalize it to have length 1 if you want

#

(b-a)/||b-a||

spring creek
half cosmos
#

is this what you mean by a twisted torus?

brazen perch
#

Does anyone have a list of commonly used lines of code

wide terrace
half cosmos
#

variables, if, else, for loops, functions...

#

assignment, declarations...

vale bridge
#

Does IL2CPP AoT have strictly superior performance compared to JiT mono? I've read that it reduces overhead during startup of the game, but haven't found much concrete information beyond this

cosmic rain
hasty wave
#

Is there any way I could make it so that a UI behind another UI cannot be interacted with if the mouse is over the front UI?

wide terrace
#

I've used a big ol' transparent panel for that purpose, in the past

wide terrace
#

I'm using an asset to render (P)React to UI Toolkit 🙃

I have yet to dig into layering separate UIs though

#

But coming from a web background, absolutely in love with the workflow

foggy pasture
#

heya, I have a camera rendering question
I'm making a game that uses pixel-perfect outlines all over the place. that works great, but my problem is that I want to be able to shift the camera" closer" to the player without increasing the size of the pixels. orthographic size, unfortunately, does what I want in terms of zooming in, but it also makes pixels proportionally larger

#

is the only way to solve this issue rendering to a render texture, scaling it up, and displaying it to the screen?

#

I ask mainly because it seems super inefficient to "record" twice as much map as is actually shown to the screen

hidden flicker
#

turning is fine, moving is fine, but doing both at the same time causes problems

tawny elkBOT
hidden flicker
#

yes it's the child of a rigidbody but setting the position manually should help override that right

rigid island
#

where is movement script

hidden flicker
rigid island
#

there is a lot gooing on in the movement script lol make sure you debug the direction values

#

im guessing at some point you're applying forward vel to something that might be rotating on the pitch

#

make sure this is being applied also to correct object yea
transform.localEulerAngles = new Vector3(xRotation, 0, 0);

#

or maybe one of the projected vectors

hidden flicker
#

like the pitch axis?

#

if so, then i’m not

#

the only thing i’m adding force to is the player rigidbody which has its axes locked except for yaw

hidden flicker
rigid island
#

is it just happen when you move / look at same time?

rigid island
hidden flicker
#

the rotation is what i expect it to be, yes

half cosmos
#

can i put multiple materials in a mesh renderer like this and then choose a material dynamically?

#

or is it gonna try and render all the materials at once

hidden flicker
#

but there’s a better way

#

just store it in a list or array

half cosmos
#

like in a public variable in a script?

hidden flicker
#

[SerializeField] private List<Material> objectMaterials = new List<Material>();

#

I think

#

Roughly that

half cosmos
#

will that show up in the inspector or do i need to like load the asset somehow?

hidden flicker
half cosmos
#

ah okay

#

thanks

hidden flicker
chrome schooner
#

If every spawning object made using prefab. Then in what case we should make a new class and constructor?

cosmic rain
granite bone
worthy wedge
#

When importing "Starter Assets character controller" getting error StarterAssetInputs could not be found.

Please help!!

thick dune
#

Sounds like a script did not transfer with the rest of the controller. You can try reimporting it or trying to see where they got that controller from or making it yourself.

worthy wedge
thick dune
#

That's great. Sometimes putting assets into an empty project and moving it over is the best answer.

last island
#

This assigns the "Type Mismatch" in the editor for some reason:

thumbnailTexture = AssetPreview.GetMiniThumbnail(prefab);
thumbnailData = thumbnailTexture.GetRawTextureData();
thumbnailWidth = thumbnailTexture.width;
thumbnailHeight = thumbnailTexture.height;
thumbnailPreview = Sprite.Create(thumbnailTexture, new Rect(0, 0, thumbnailWidth, thumbnailHeight), Vector2.zero);

It feels like it shouldn't? The thumbnailPreview becomes what seems to be a valid sprite when I step through breakpoints.
But it becomes "Type Mismatch" instead.

cosmic rain
last island
#

Type mismatch

#

And I am not sure why

cosmic rain
#

What type is ThumbnailPreview?

last island
#

Sprite

cosmic rain
tawny elkBOT
last island
cosmic rain
#

The whole script I mean

last island
# cosmic rain The whole script I mean

Due to this being work, no. I can't.
I can share snippets.

But even if I shared the rest of the script, it won't change anything. The code snippet I sent is the whole thing.
I want to call the method and generate a sprite from the resulting Texture2D. That's it.

cosmic rain
last island
#

What is it you are looking for?

cosmic rain
#

The actual type you're using for the field. There's a chance that it's a type from a different namespace for example.

last island
#
[SerializeField] private Texture2D thumbnailTexture;
[SerializeField] private Sprite thumbnailPreview;
#
using System;
using UnityEditor;
using UnityEngine;
last island
#

Yep

cosmic rain
#

Okay🤔

last island
#

I'm just as confused as to why it doesn't work.

cosmic rain
#

Are you using a custom inspector/editor perhaps?

last island
knotty sun
#

if you are making the sprite from the texture why is the Sprite even serialized?

last island
#

It's just to preview the sprite in the editor

#

I could do with the texture but couldn't think of a way to use the texture in a scriptableobject to achieve that

#

So I thought maybe I could use a sprite instead

knotty sun
#

so show the inspector of the texture

last island
#

the inspector of the texture

#

What does that mean?

cosmic rain
last island
knotty sun
last island
knotty sun
#

just select the texture asset in the project view and screenshot it's inspector

last island
#

But it's not a texture asset. It's generated by using the Asset Preview AssetPreview.GetMiniThumbnail(prefab);

knotty sun
#

this is an asset is it not?

last island
#

In my asset folder? No.

cosmic rain
#

You can double click it

#

To open it's inspector

last island
knotty sun
#

well there you go, you are trying to make a sprite from something that cannot be converted to a sprite

cosmic rain
#

Btw, does the issue persist if you use a debug mode inspector?

last island
#

It's a Texture2D that Unity itself generated.

cosmic rain
#

And if that was the problem, they'd just get a null reference instead

knotty sun
last island
#

Please elaborate.

#

What Texture2D, valid as it is, cannot become a Sprite?

cosmic rain
#

It would've been a valid point, if you were getting a null instead.

last island
#

That's what I'm thinking too

cosmic rain
#

Can you take a screenshot with a debug inspector?

dusky lake
#

Is there a way to listen to the OnDrag event of a scrollrect from the outside?

cosmic rain
last island
#

Well given the data that's put in the thumbnail data array, it appears that a texture is made.
But it just won't create a Sprite from it 🤷‍♂️

#

Or, well, it does

#

But it's seen as a Type mismatch

cosmic rain
#

In the debugger too?

#

When you step through the code

wild vigil
#

cullinggroup currentDistance is always 0. How can I get this to work?

orchid yacht
#

Hi! I have a question: is it normal practice to organize files into folders in a project? I find it convenient because I can access any class or dependency from anywhere in the application. I’m not sure how others generally do it. Should I expand this organization? UI/SCENE

vapid anvil
#

Hi guys, how u doing ?
I'm using Synty Characters for my game. As i use mixamo animations, i need to use avatar to make my animations work. Nevertheless, i'm also using animation rigging package to make my own animations. But, now, as i use an avatar on my animator, i can't reference my rig anymore. Does anyone have a solution?

vapid anvil
#

sorry

fervent snow
#

hey all, not sure where the right place to ask this is. I'm in love with the appearance of GLLines in game, and I think they are terrific to convey info to the player. My issue is that they are cumbersome to work with. Does anyone know if any assets or git repos for a GLLinesManager class of some kind that doesn't suck(has minimal impact on performance)? Ideally I'd use it to draw just some basic lines and circles

thick terrace
plucky inlet
#

Hello everyone, i was trying to use unitys webcamtexture on visionos to get the persona, but for some reason, the material stays white. The problem I have right now is this docs page: https://docs.unity3d.com/Packages/com.unity.polyspatial.visionos@1.2/manual/WebCamTextures.html

MarkDirty does not take webcamtextures as a type, so I tried to copy the texture from the webcam to a rendertexture and update that, but i guess, that does not do the trick of updating the webcamtexture still.

Graphics.CopyTexture(texture, renderTexture);
PolySpatialObjectUtils.MarkDirty(renderTexture);
crude mortar
# fervent snow hey all, not sure where the right place to ask this is. I'm in love with the app...

https://assetstore.unity.com/packages/tools/gui/aline-162772 https://arongranberg.com/aline/features There is ALINE for in-game / editor high performance gizmo drawing, however it does have antialiased lines. Not sure what specifically is appealing about GL lines to you, but if it's their aliased nature then you might just have to set up your own GL drawer. ALINE also costs money, but you could look into the features and see if it's interesting to you.

#

I personally use it for debugging tools but I can imagine it could be used for in-game UI with the right art style

vagrant moon
#

Transform have unexpected behaviour regarding passing it as "in" parameter:
since Transform is Reference type it only should disallow to reassign new value to it. so expected behaviour in general is: ```C#
var my = new MyClass();

void ChangeMyObject(in MyClass myObject)
{
myObject.Value = 3;
}

Console.WriteLine(my.Value); // 0

ChangeMyObject(my);

Console.WriteLine(my.Value); // 3

class MyClass
{
public int Value { get; set; }
}ButC#
public void OnUpdate(in Transform cursorTransform)
{
cursorTransform.position = transform.position;
}``` do not change position of object :/

  • before any one ask: OnUpdate is called properly in some other place that I omitted here I double checked it with some Debug.Log
leaden ice
#

likely your obejct has a CharacterController or an animator or something

rigid island
leaden ice
#

that being said, there's no reason to pass Transform as an in param.

vagrant moon
#

its just a squere with my one script

leaden ice
#

more debugging will help

#

and/or sharing more context

wary coyote
#
    private void GenerateTwistedTorusWithoutNormalVector()
    {
        for (int i = 0; i < thetaDivisions; i++)
        {
            float phi = 2.0f * Mathf.PI * i / thetaDivisions;

            thetaCenters[i] = new Vector3(majorRadius * Mathf.Cos(phi), majorRadius * Mathf.Sin(phi), 0f);

            for (int j = 0; j < phiDivisions; j++)
            {
                float theta = 2.0f * Mathf.PI * j / phiDivisions;
                float majorRadiusTwist = _offsetAlignment.x * j / phiDivisions;

                float twistedTheta = theta + minorRingTwistIncrement;
                float x = (majorRadius + minorRadius * Mathf.Cos(twistedTheta)) * Mathf.Cos(phi + majorRadiusTwist);
                float y = (majorRadius + minorRadius * Mathf.Cos(twistedTheta)) * Mathf.Sin(phi + majorRadiusTwist);
                float z = minorRadius * Mathf.Sin(twistedTheta);

                Vector3 position = new Vector3(x, y, z);
                Vector3 direction = (thetaCenters[i] - position).normalized;

                Quaternion rotationQuaternion = Quaternion.LookRotation(direction);

                vertices[i * phiDivisions + j] = position;
                rotations[i * phiDivisions + j] = direction;
                rotationQuaternions[i * phiDivisions + j] = rotationQuaternion;

                Debug.DrawRay(position + transform.position, direction, Color.red);
            }
        }
    }```

                Quaternion rotationQuaternion = Quaternion.LookRotation(direction); is giving me the wrong euler rotation but I am not experienced with quaternions enough to know why its wrong or how to adjust it to fix it. Pictured is how its wrong, expected is they all point towards the center but together on the same axial plane
#

How do I adjust / replace:

With something that will correctly LookRotation at my point without twisting the rotation weirdly?

#

I am guessing what it needs is an Up vector, but I am uncertain how to determine what that value should be

leaden ice
wary coyote
#

I am guessing its up 'around' the major radius? But what is that as a vector

leaden ice
#

it's a little unclear from the picture here exactly what you want but you'd probably want something like the normal of the "ecliptic plane" of each circle if you get what I mean

leaden ice
#

probably you can take the cross product of the direction from the center to the center of the little circle and world forward

#

or like "big circle forward"?

#

e.g.

Vector3.Cross(thetaCenters[i], Vector3.forward)``` maybe?
wary coyote
#

the terms I am using are major radius and minor raidus to refer to major being from the center point of all of it to the torus outer ring, and minor being around that ring 🤔

leaden ice
#

it will break if the "major" circle needs to rotate though

wary coyote
#

Ah yes I see what you mean

leaden ice
#

nice

wary coyote
#

Worked like you said, until rotated

leaden ice
#

oh

#

not nice lol

wary coyote
#

That's still better than what I had when I started

leaden ice
#

well they will need to rotate as the big thing rotates

#

you'll need to recalculate it

wary coyote
#

reticulate my splines

leaden ice
#

or you could just child them to the center and rotate the center

wary coyote
#

Im doing a ton more rotations and positions after this so the childing thing wouldn;t work here, so I will look into calculating theta cross per child instead of per thetan

leaden ice
#

Biblically accurate angel

wary coyote
#

some of the movements when its not a cubes (which don't cirrently orient due to the above code missing that we're working on)

#

I changed the math to use world for everything in world space and then transformed to local space only after so that rotation was still correct
2/3 axises now behaving as desired

#

the last axis to fix is the twist shown here, each one still targets its original theta ring center point, but I have to recalculate the theta ring center point as an offset around the theta on an individual basis 🤔

leaden ice
#

nice

half cosmos
#

😮

wary coyote
unborn oracle
#

My game works fine 0 error in the editor, but when I build the game, I get an "object reference not set to an instance of an object" error. This error does not occur in the editor, only when I play the game in the build. The code where this error occurs is as follows: void Update()
{
if (playerHealthbar.isDead == false && Time.timeScale != 0f)
{
if (spellCaster.Casted == false && Input.GetMouseButtonDown(0) && meleeStateMachine.CurrentState.GetType() == typeof(IdleCombatState))
{

            // anim.SetBool("isAttacking", true);
            meleeStateMachine.SetNextState(new GroundEntryState());


        }
    }

} (  if (spellCaster.Casted == false && Input.GetMouseButtonDown(0) && meleeStateMachine.CurrentState.GetType() == typeof(IdleCombatState)) this part is the error i get )
leaden ice
#

Also !code for posting code here

tawny elkBOT
unborn oracle
unborn oracle
tawny elkBOT
unborn oracle
#

!code cs if (spellCaster.Casted == false && Input.GetMouseButtonDown(0) && meleeStateMachine.CurrentState.GetType() == typeof(IdleCombatState))

tawny elkBOT
leaden ice
#

it's explaining hjow to format your code

tawny elkBOT
leaden ice
#

stop typing the code command lol

#

READ IT

unborn oracle
#

oh sorry lol

#

wait im reading sorry 🙂

#

cs if (spellCaster.Casted == false && Input.GetMouseButtonDown(0) && meleeStateMachine.CurrentState.GetType() == typeof(IdleCombatState))

#

here is part where i get error

leaden ice
#

Ok it's a basic NRE

#

so either:
spellCaster
meleeStateMachine
or
meleeStateMachine.CurrentState are null

#

use logs or the debugger to find out which, and resolve it

#

And yes I understand this is only happening in your build. That doesn't change anything

unborn oracle
#

like what ? i added debugs and i did get nothing

leaden ice
#

It's probably happening in the build only due to script execution order issues

leaden ice
unborn oracle
#

wait let me try it again

leaden ice
#

you're supposed to read the log output to determine which thing is null

compact fog
#

So ive tried this multiple ways and I am unsure of where the issue is. I have a scriptableobject that has the following variables (tried two ways)

Attempt 1:

    [HideInInspector]
    public BaseAnimationController baseAnimationController { get; protected set; }

Attempt 2:

    protected BaseAnimationController _baseAnimationController;
    public BaseAnimationController baseAnimationController => _baseAnimationController;

Both result in it still being shown in the inspector which I don't want as it's programmatically assigned

leaden ice
knotty sun
compact fog
unborn oracle
#
    {
        if (playerHealthbar == null)
            Debug.LogError("playerHealthbar is not assigned.");
        if (spellCaster == null)
            Debug.LogError("spellCaster is not assigned.");
        if (playerMovement == null)
            Debug.LogError("playerMovement is not assigned.");
        if (meleeStateMachine == null)
            Debug.LogError("meleeStateMachine is not assigned.");
    }``` i added this debugs and none of them are null...
leaden ice
#

why are you checking in start

#

you need to check right before the error happens

#

You're also not checking meleeStateMachine.CurrentState

#

which is one of the things that could be null

unborn oracle
#

okey sorry for that let me check again

#

oh now i get message bc of the meleeStateMachine.CurrentState is null when i try it on build

#

I don't understand why I'm getting the error even though the StateMachine is a public variable and I assign it manually. Could the issue be due to the StateMachine code?

leaden ice
#

and hasn't been set by the time you try to access it

#

that is the problem

unborn oracle
#
using UnityEngine;

public class ComboCharacter : MonoBehaviour
{
    public SpellCaster spellCaster;
    public PlayerMovement playerMovement;

    public DamageSword damageSword;
    public PlayerHealthbar playerHealthbar;
    public Animator anim;
    public StateMachine meleeStateMachine;

    public Collider2D hitbox;
    // [SerializeField] public GameObject Hiteffect;
    void Update()
    {
        if (playerHealthbar == null)
            Debug.LogError("playerHealthbar is not assigned.");
        if (spellCaster == null)
            Debug.LogError("spellCaster is not assigned.");
        if (playerMovement == null)
            Debug.LogError("playerMovement is not assigned.");
        if (meleeStateMachine == null)
            Debug.LogError("meleeStateMachine is not assigned.");
        if (meleeStateMachine.CurrentState == null)
            Debug.LogError("meleeStateMachine.CurrentState is null");

        if (playerHealthbar.isDead == false && Time.timeScale != 0f)
        {
            if (spellCaster.Casted == false && playerMovement.isPlayerInteractsWithNpc == false && Input.GetMouseButtonDown(0) && meleeStateMachine.CurrentState.GetType() == typeof(IdleCombatState))
      {

        // anim.SetBool("isAttacking", true);
        meleeStateMachine.SetNextState(new GroundEntryState());
      }
     }
    }
    public void Attack2True()
    {
        damageSword.Attack2 = true;
        damageSword.Attack1 = false;
        damageSword.Attack3 = false;
    }
    public void Attack3True()
    {
        damageSword.Attack2 = false;
        damageSword.Attack1 = false;
        damageSword.Attack3 = true;
    }
    public void Attack1True()
    {
        damageSword.Attack2 = false;
        damageSword.Attack1 = true;
        damageSword.Attack3 = false;
    }
    public void FinishAttack()
    {

        anim.SetBool("isAttacking", false);
    }
    public void StartAttack()
    {
        anim.SetBool("isAttacking", true);
    }
}
knotty sun
#

!code

tawny elkBOT
unborn oracle
#

do you want to see the stateMachine script also ?

knotty sun
#

only if you post it correctly

unborn oracle
#

public class StateMachine : MonoBehaviour
{
    public string customName;

    private State mainStateType;

    public State CurrentState { get; private set; }
    private State nextState;

    // Update is called once per frame
    void Update()
    {
        if (nextState != null)
        {
            SetState(nextState);
        }

        if (CurrentState != null)
            CurrentState.OnUpdate();
    }

    private void SetState(State _newState)
    {
        nextState = null;
        if (CurrentState != null)
        {
            CurrentState.OnExit();
        }
        CurrentState = _newState;
        CurrentState.OnEnter(this);
    }

    public void SetNextState(State _newState)
    {
        if (_newState != null)
        {
            nextState = _newState;
        }
    }

    private void LateUpdate()
    {
        if (CurrentState != null)
            CurrentState.OnLateUpdate();
    }

    private void FixedUpdate()
    {
        if (CurrentState != null)
            CurrentState.OnFixedUpdate();
    }

    public void SetNextStateToMain()
    {
        nextState = mainStateType;
    }

    private void Awake()
    {
        SetNextStateToMain();

    }


    private void OnValidate()
    {
        if (mainStateType == null)
        {
            if (customName == "Combat")
            {
                mainStateType = new IdleCombatState();
            }
        }
    }
}
leaden ice
#

you're not setting CurrentState until the first Update is called for StateMachine

severe mirage
#

hey guys

leaden ice
#

Simply, ComboCharacter's Update is running before the one on StateMachine, hence CurrentState is not yet set @unborn oracle

unborn oracle
#

oh then what should i do to fix that

leaden ice
#

make sure CurrentState is set earlier

#

I would set it to an initial state in Awake

severe mirage
#

when i try to export my game it gives me compiler errors

leaden ice
leaden ice
knotty sun
spring creek
unborn oracle
leaden ice
#

Right now you're doing this "SetNExtStateToMain thing in Awake

#

which is... weird

#

why don't you just directly set the state to the starting state there?

#

e.g.

SetState(mainStateType);```
#

the whole "nextState" system you have is kind of weird

#

your state machine should never not be in any state

unborn oracle
#

Thank you soo much now i fix it thanks to you ❤️

unborn anchor
#

Hey everyone I Have an optimization pb. I'm making a turn based game and in my battle manager I have a coroutine that manage the battle.

It looks like this

private IEnumerator Turn()
{
    yield return new WaitUntil(LoopCanStart);
    InitialiseBattle();
    while (true) 
    { 
        StartTurn();
        playerInstance.StartTurn();
        _playerTurn = true;
        Debug.Log("Before WaitPlayer turn");
        yield return new WaitWhile(()=>_playerTurn );
        "End Of Player Turn".ColorDebugLog(Color.black);
        playerInstance.EndTurn();

        opponentInstance.StartTurn();
        OpponentTurn();
        yield return new WaitWhile(() => _opponentTurn );
        opponentInstance.EndTurn();
        yield return new WaitForEndOfFrame();
    }
}

the thing is each time I press the button that make _playerTurn true the coroutine take more and more time to load up to 1/2 min at the end and I have no Idea why.

The function called are very simple (variable check and little value change)

Does someone have any idea ?
Thanks in advance !
(picture of the profiler in my next msg)

simple saffron
#

getting the weirdest thing rn
trying to increment a float that's part of a struct, and its quite simply just not

#

however, the rest of the code is executing, because it snaps the position of this object back to where the struct's data says it should be

unborn anchor
#

What is the context ? struct are not serialized object so if you try to increment it by ref or something like that it will not do anything

simple saffron
#

oh, right

unborn anchor
#

Can you share your code maybe ?

leaden ice
simple saffron
#

I've just changed it to a class
im coding tracers for bullets. every fixed update, it should move the tracer along the path between a start and end point. I think using structs may have been my mistake

unborn anchor
leaden ice
#

show your code?

simple saffron
#
        public class Tracer
        {
            public Transform tracer;
            public float t;
            public float distance;
            public Vector3 start, end;
            public float increment;
        }

the struct

leaden ice
#

that's a class

#

not a struct

#

show your full script(s)

simple saffron
#

sorry, i changed it a moment ago

#

until about 2 minutes ago, it was a struct.
the code for lerping the tracer between start and end

                tracers.ForEach(x =>
                {
                    if (x.tracer != null)
                    {
                        x.tracer.position = Vector3.Lerp(x.start, x.end, x.t);
                    }
                    x.t += x.increment * Time.fixedDeltaTime;
                });
leaden ice
#

you can't do Foreach

#

you need a regular for loop

#

and then you would:

  • copy the struct out of the list/array
  • modify it
  • write it back into the list/array
#

e.g.

for (int i = 0; i < tracers.Count; i++) {
  Tracer tracer = tracers[i];
  tracer.something = something;
  tracers[i] = tracer;
}```
#

otherwise you're just modifying your local variable

simple saffron
#

now that its a class, it works just fine

leaden ice
#

sure but it will be less efficient

#

but yeah you are missing the fundamental understanding here of the difference between classes and structs

#

i.e. how value types work vs reference types

indigo tree
#

Never really though about this before but for scriptable objects but should you encapsulate scriptable object properties or just make them public?

indigo tree
spring creek
unborn anchor
gray mural
#

I find it useful to think about properties as any other variables or methods.
If you need a property, which can be accessed outside of the class, make it public, otherwise, it can stay private. For example, when you have a WorldMousePosition property in your Player class, which returns the converted Input.mousePosition using the main Camera. Surely, it can be a method, but it does not matter if there is no parameter required.
It makes sense to still start a property from the capital letter, regardless of its access modifier, and make sure you also create a variable, assigned to the required property, to reduce the performance as much as possible, as you would've done it using a method

wide terrace
unborn anchor
indigo tree
# gray mural <:itdepends:1108023708695662672>

Okay, so lets say I have a variable called "characterName" in my character scriptable object.
No other scripts will change this variable.
I could encapsulate it as so:

  private string characterName = string.empty;
  public string CharacterName => characterName;   

or just do it like this:

  public string characterName = string.empty;
unborn anchor
#

Right now I'm trying something else

while (true) 
{ 
    StartTurn();
    playerInstance.StartTurn();
    _playerTurn = true;
    Debug.Log("Before WaitPlayer turn");
    while(!_playerTurn)
    {
        yield return _waitForEndOfFrame;
    }
    "End Of Player Turn".ColorDebugLog(Color.black);
    playerInstance.EndTurn();

    opponentInstance.StartTurn();
    OpponentTurn();

    while (!_opponentTurn)
    {
        yield return _waitForEndOfFrame;
    }
    opponentInstance.EndTurn();
    yield return new WaitForEndOfFrame();
}

And i stored _waitForEndOfFrame

spring creek
indigo tree
wide terrace
spring creek
gray mural
unborn anchor
gray mural
unborn anchor
indigo tree
unborn anchor
gray mural
wide terrace
spring creek
indigo tree
spring creek
#

Oh. Missed that that was said already

unborn anchor
indigo tree
knotty sun
unborn anchor
rugged storm
#

how can i check if a ray cast is hitting a 2d Sprite in a 3d game? more specifically how can give that sprite a polygon collider 2d like collider that works with the raycast?

indigo tree
#

Ty

unborn anchor
wide terrace
gray mural
rugged storm
#

oh the raycast wasn't detecting it but after more testing i think that may be an issue with the raycast?

unborn anchor
#

Or something like that

spring creek
unborn anchor
rugged storm
#

but it worked when i used like a box collider

gray mural
rugged storm
#

no, im using sprites in a 3d game,

gray mural
#

It doesn't seem like the issues is in PolygonCollider2D not reacing to raycasts

gray mural
rugged storm
#

does the mesh collider wrap to the sprite in the same way the polygon collider does?

wide terrace
# unborn anchor

I do not - I'm not terribly experienced in this capacity 😅

But you might be able to flip on some additional info for GC.alloc from the "Call Stacks" dropdown at the top, if you haven't already.

The Memory Profiler might also provide some insights

lean sail
# unborn anchor

Didnt really see anything above but turn on deep profile for more info and run it again

rugged storm
# gray mural Yes, but in 3D

i don't know how to make it do that? the closest thing is giving it a quad mesh at which point its no better than a box collider across the whole area of the sprite which includes empty space

unborn anchor
#

Much much more info thanks !!! I think i can identify the pb from here

rugged storm
#

actually a quad in the mesh collider dosent get detected either but other meshs do

gray mural
#

But this is a bad idea

#

If that's a sprite, use a PolygonColider2D with the Physics2D's Raycast

rugged storm
#

Oh im not using a physics2D Raycast i see

unborn anchor
# unborn anchor

SOLVED : thanks everyone ( I was adding a new delegate at each loop so at the end I was calling 1800000 time the same function x) )

hexed geode
#

yo if i destroy a gameobject will any references to it become null

wide terrace
hexed geode
#

i see

#

also how would i detect if something is not being hovered?

#

i wanna make a message show up when i hover over a button and for it to disappear when im not hovering

wide terrace
#

OnMouseExit() may be sufficient here

hexed geode
#

oh right

#

i can do the spawning in OnMouseEnter() too then

#

and deleting it in Exit

#

and i dont even need messageExists then i guess?

#

as a safeguard maybe but still

wide terrace
#

Probably not 🙃

hexed geode
#

i dont need either bools actually

gray mural
#

Enable or disable the message depending on the method

wide terrace
# hexed geode i see

One minor addendum: when you Destroy() an object it won't actually happen until the end of the current frame. DestroyImmediate() does it instantaneously, but at the cost of immediately incurring that overhead as well

hexed geode
#

wdym by incurring the overhead

gray mural
#

It means don't use unless in the editor

wide terrace
# hexed geode wdym by incurring the overhead

Allocating things in memory and the "Garbage Collection" process through which destroyed objects' memory is marked as free are relatively expensive operations - both have a more notable performance impact than most other common operations and calculations. It's generally not a problem in small quantities, but it can become problematic at scale... Many the cause of a performance bottleneck is unintentionally mucking about with memory much more than you intended to 👀

As sashok says, DestroyImmediate() is best avoided apart from editor scripting

hexed geode
#

ok what im confused about it is

#

why does OnMouseEnter() not work for UI objects

broken light
#

if you have a prefab and place it in the scene and you want to modify the mesh based on its unique setup from inspector - how can you do that in edit mode since unity tells you to only use shared mesh but that will affect all the prefabs not just the one specific object

hexed geode
cold parrot
hexed geode
gray mural
hexed geode
#

maybe adding colliders to ui objects isnt a good idea lmao

gray mural
#

Actually, IPointerHandlers are so bad..

#

Then don't really provide a great drag functionality

gray mural
#

Someday I may implement my own interface for drag when I have to use it

hexed geode
#

😭

#

i will try to read docs and forums more before asking questions in the future ty

#

it works, nice :)

gray mural
#

I have these properties in my Editor script.

public PlayerBuildSetup BasicSetup => Target.BasicSetup;
public PlayerBuildSetup AddArrowSetup => Target.AddArrowsSetup;
public PlayerBuildSetup MoveArrowSetup => Target.MoveArrowsSetup;

Each property has its own method, like ExecuteBasic(evt) for BasicSetup and ExecuteKey(AddArrowSetup, evt) for AddArrowSetup.
Their return types are booleans. If false is returned, the PlayerBuildSetup.Break() method should be called on the previous setup, which is unique at a time, and the "loop?" should be broken too.
I know I'm overthinking it, even wanted to enumerate through an IEnumerator with MoveNext, but how would you implement this in a clear way?

#

More setups may be added in the future, so the solution should be persistent

hexed geode
hexed geode
#

wait lemme try something real quick

hexed geode
# gray mural What do you mean?

well say i wanna spawn a UI object when i hover over a button
the obejct spawns, blocks the button, instantly disappears, opening the button, which means the button is being hovered again and the object spawns again repeating the cycle

#

and i wonder if theres any way to like, stop the object from being "seen" i guess

#

i would assume IgnoreRaycast layer wouldnt work? lemme try at least

#

nope as expected

wide terrace
#

Many uGUI objects have a "Raycast Target" toggle

hexed geode
hexed geode
# gray mural What do you mean?

what am i missing? i can't get any info about the new object it's pointing at during OnPointerExit, i cant edit what layer im ignoring (unless i can), what do i do

#

ig ill watch a tutorial

dense shale
#

never mind needed to import it

restive anchor
#

I keep getting a CS1513 even though there's a curly brace at the line mentioned.

rigid island
#

show the error

#

codes are for computers

restive anchor
rigid island
#

if its a syntax issue then you need to make sure your IDE is configured

#

!ide

tawny elkBOT
rigid island
#

pretty obvious its expecting a }

#

it will tell you exactly where to add

restive anchor
#

I already have a } there

rigid island
#

im gonna take a wild hail mary guess its the class enclosing brace

#

your IDE def is not configured so fix that

dense shale
#

how much should i subdivide my code into functions? should I have a ProcessAnimation, ProcessInput, ProcessSound etc function and call them all in Update()?

#

or should i just put it all in update separated by newlines

little meadow
#

it doesn't matter... whatever makes your team happier

#

you can probably refactor this in about a minute in each direction when there's a need, so not worth spending more than 10 seconds to decide 😄

#

my approach tends to be: write everything directly in Update if it's just a few lines of code or would be one function anyway... if it starts to be long and somewhat complicated - splitting it better expresses what each part is about

left tinsel
#

I don't understand what this error code is saying

little meadow
#

something is null on line 17 of that SomethingSomethingBase class

rigid island
#

MoveNext() just makes it look somewhat "scary" because its happening inside a Coroutine thats all

#

since its an iterator

quiet kestrel
#

Hey does anyone know how to create a list like the one you get when you add a component in the editor?

half cosmos
#

i have a game object with a lot of child objects that it needs to manage...
i could build it all as a prefab, but then the script needs to get references to all the children
or i could instantiate all the child objects within the script - then i'd have references to them already, but it's not as nice to look at in the scene

#

what should i do?

wide terrace
wide terrace
quiet kestrel
#

I am currently figuring it out how it works

wide terrace
shell scarab
quiet kestrel
#

took me a bit to find since I had to paruse unity's Editor api for volume component

#

since idk how to find the one for adding components

#

though if you want to see how the volume component does it, make sure you have unity core RP installed

#

that's where it comes from

elfin ridge
#

!cs

tawny elkBOT
half cosmos
#

actually you're right it's nice to be able to look at it in the hierarchy too

shell scarab
half cosmos
#

does it make sense to drag a game object's child to the input on its own script like this?

#

people were saying the GetChild() functions were fragile and it's better to have stuff hooked up through the inspector

#

i've hooked up stuff from the project assets (on the bottom side of the screen) before, but i'm not sure if it's ok to do it from the hierarchy like this?

#

i think this is what they were suggesting as an alternative to GetChild()

oblique spoke
#

Yea it's good with scene objects too when available.

shut ridge
#

Heya. I've been working with FixedJoint2Ds on rigidbodies with negligible mass (~0) and trigger boxcollider2ds. I've noticed that when the fixedjoint skeleton impacts another collider, the set of trigger boxcolliders jerk into the collider they're supposed to be colliding with for a single frame and then adjust back into their normal position over the next few frames. The problem is that I have a physics-intensive project where this few-frame bug ruins everything. How can I make the fixed joints actually... fix?

half cosmos
oblique spoke
#

Correct.

half cosmos
#

oh or did you mean...

#

sorry i have to go eat dinner

#

thanks!

timid briar
#

Hii

left tinsel
#

I'm trying to code it to where each line will play separately and I've tried changed the delay between lines but it isn't work either and I'm getting no errors so idk what the issue is?

shell scarab
#

you have a god old logic error!

#

let's see

shell scarab
#

lmk if you need more help!

shell scarab
#

no, if you look this will wait in the middle of the loop that is disabling all your dialogue objects and so Start will still run on those not disabled.

left tinsel
#

OHHHHh

shell scarab
# left tinsel OHHHHh

lmk if you get it! If you can't get it I can give you the code but it's important to learn to debug your code!

half cosmos
#

can an Action have a return type?

#
        bool requestNewState(int handleIndex, bool newState) {
            if (!newState) {
                if (activeHandleIndex != handleIndex) {
                    Debug.LogError("Permutor got into illegal state!");
                    return false;
                }
                activeHandleIndex = -1;
                return true;
            }
            if (activeHandleIndex != -1) return false;
            activeHandleIndex = handleIndex;
            return true;
        }
        for (int i = 0; i < workingRows; i++) {
            handles[i].Init(i, requestNewState);
        }

this isn't working

shell scarab
half cosmos
#

those are the inputs

#
    public void Init(int handleIndex, Action<int, bool> callback) {
        state = false;
        this.handleIndex = handleIndex;
        requestNewState = callback;
        animator = GetComponent<animator>();
        animator.SetBool("initialized", true);
    }
shell scarab
#

no they are not

#

in the Func class, the last generic type is the return type.

half cosmos
#

ohhhhh

#

but i was using 2 type parameters before when it was void return type

#

oh you pointed me to func not action

shell scarab
#

what class were you using?

half cosmos
#

i was using action

#

Action

shell scarab
#

yea

#

real quick, how are you using it?

shell scarab
half cosmos
#

i'm not sure what that means

shell scarab
half cosmos
#

yeah let me just give that whole class since it's small

#
public class PermutorHandle : MonoBehaviour
{
    private bool state;
    private int handleIndex;
    private Action<int, bool> requestNewState;
    private Animator animator;

    public void Init(int handleIndex, Action<int, bool> callback) {
        state = false;
        this.handleIndex = handleIndex;
        requestNewState = callback;
        animator = GetComponent<animator>();
        animator.SetBool("initialized", true);
    }

    void OnMouseDown() {
        if (!requestNewState?.Invoke(handleIndex, !state)) return;
        state = !state;
        animator.SetBool("active", state);
    }
}
shell scarab
#

ok yea cool, just wanted to check you weren't trying to do something funky like an event with a return type.

half cosmos
#

this is a child object talking to its parent

#

i'm not sure what you mean, requestNewState does return a bool

#

but as long as it looks good to you

#

🙂

shell scarab
#

yes, but delegates are often used with events, and an event does not return anything, so I wanted to see how you were trying to use it to make sure that was not the case.

half cosmos
#

i'm getting this error
Assets/Permutor/PermutorHandle.cs(22,13): error CS0266: Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)

#

that's on the line with Invoke()

#

oh do i not need that ? syntax for Funcs?

#

woo no compile errors

#

thanks

shell scarab
#

no you should definitely have the ? or null check it in some way

#

im not sure about the specifics but for some reason it won't cast ? to a bool in the if statement (i think for numbers it does just fine tho?). You can just do this:

if (requestNewState?.Invoke(handleIndex, !state) != true)
left tinsel
somber nacelle
#

it can be null checked on a separate line though and then invoked for the if statement just fine

shell scarab
#

oh yea huh. If they did if (requestNewState?.Invoke(handleIndex, !state) != true) it would work cus null is not true duh (this is also why it works in other situations but not bool cus I shorthand it a lot).

somber nacelle
#

well no, that would have the same error because you're still trying to cast a nullable bool to bool. you cannot use the null conditional operator in the condition because of that. so it just needs to be null checked separately either as a guard clause on the previous line or as the first condition of the if statement if(requestNewState != null && requestNewState.Invoke(...))

shell scarab
shell scarab
#

it's just that you normally wouldn't compare two different types because it always returns false (unless one type can implicitly cast to the other)

#

ok well i guess it's true a little bit. I think it's with value types and not reference types, my mistake. Or maybe it's that null can compare to any type? Whatever the case, null can compare.

Ok, so it's true a little bit. You don't have to cast when you compare something to null because it always returns false.

somber nacelle
#

no, the first works because Nullable<T> likely has the equality operators overridden not just because null can be compared to other objects

shell scarab
#

null can be compared to other objects, 100%

somber nacelle
#

i'm not saying it cannot

#

i'm saying that the reason bool? != bool works is because Nullable<T> likely has the equality operators overridden. (bool? is literally just shorthand for Nullable<bool>)

shell scarab
#

yes I know, but in your original message you said I'd have the same error bc of casting. We were both a little wrong :)

half cosmos
#

i've gotta read this tomorrow, my mind is fried right now lol

somber nacelle
shell scarab
steep snow
#

There any kinda of global setting to cap Unity's memory usage? I dialed a variable up too high and before I could figure out what was even going on it had sucked up 20 gigs on me

cosmic rain
steep snow
#

looks like one alternative is to setup a coroutine that checks System.GC.GetTotalMemory() and if above some level just call Application.Quit() and log a message

cosmic rain
#

I don't think Application.Quit works in the editor.

#

But you could throw an error I guess.

steep snow
#
    private void EndGame()
    {
        Application.Quit();
#if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
#endif
    }```
This seems to work
#

I could barely get task manager to pop up it was so full lol

gray mural
cunning burrow
#

for some reason, this is visible for a frame before the horizontal layout realizes it's mistake

#

forgiveness to nest haters

#

the categories content has a horizontal layout group, I need the text width to be scaled though. I just noticed content size filter has a warning for layout groups, but how do I make it so the text and the button respectively size to fit a single line of the text without wrapping

swift falcon
#

How can i Code my own 3D camera, Docs and stuff, no cinnemachine

cosmic rain
mild goblet
#

friends, I'm using unity hexagonal pointy topped tilemaps. I want to make a custom method for getting GetCellCentreWorld. I want to a custom method so i can use it in Jobs. I'm having trouble finding the resources to implement this. has anyone done anything like this?

last island
#

Quick question; If I make this field in a class public static readonly Texture2D BlankTexture = new(128, 128); does that mean that every new instance of the class has this field, meaning higher memory footprint, or would the instance be shared?

#

My gut says it's shared but just wanted to double check

amber mauve
#

does anyone know how to disable this log in unity andriod

lean sail
lilac thorn
#

yo can anyone help me

#

I have trouble w calling a function

lean sail
lilac thorn
#

then go help me there lmao

last island
lean sail
soft shard
# cunning burrow the categories content has a horizontal layout group, I need the text width to b...

Since the text is a child of the button, you can just use anchors to fill the width (and optionally the height if youd like), this will auto-size with the button - then you would only need the content size fitter (and some kind of layout group) on your button - however, layout groups refresh at specific times, so you may either need to force changes (which could take at least 1 frame to register) or you need to manually call a refresh of the layout - for a manual refresh, you can try some of the solutions mentioned here: https://discussions.unity.com/t/force-immediate-layout-update/608126/12 (either forcing the canvas to update, using a coroutine to toggle components and wait a frame, forcing the layout group to recalculate, or forcing the layout to rebuild) - alternatively if none of that works you can also calculate and position/resize elements yourself with their RectTransform and choose when to update it instead of using a layout group, albeit this approach is a bit more complicated and involves some math (but gives you more control and possibly a performance increase over the component)

mossy gust
#

i want to make a souls-like game, but im not sure where to start on the movement, and how i could get it to feel like it does in souls like games.

#

could someone help?

cosmic rain
#

Maybe start from going through the tutorials.

mossy gust
#

i tried them

#

they're either outdated

#

or just dont work

mossy gust
cosmic rain
#

most likely that

#

Unity didn't change that much in the last 10 years in terms of what you'll use for character controllers, so it's unlikely that they're outdated.

#

As for it not working, there's not much we can help you with that. You just need to go back and rewatch the tutorial and make sure you followed it correctly.

#

Also, maybe go one more step back, and go through unity basics first. That would help you identify things you might be doing wrong or missing. And actually help you understand what they're doing in the tutorials, instead of just blindly following them.

#

!learn

tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

cosmic rain
#

If there's any specific problem that you struggle with debugging, feel free to share the details.

frigid turtle
#

Hello guys, im not sure if its proper channel, but let me start from here. I do struggle with building a game for iOS since i moved from 2021.3.15f1 to 2022.3.34f1. To be more precise it finishes build but when it comes to archive stage it fails with error
ld: library 'x' not found
where x looks like my bundle identificator (mygame.dev.testflight)

#

I've read through all forums and didn't find solution yet

golden vessel
#

Hey, I've made all my game for HD res and I'm trying to set it so that there'll be black bars on the sides when there the aspect isn't 16/9.
So far I have problems with the UI and so I'm considering to switch the match with width/height depending on the aspect ratio of the resolution.
Is this a sensible way to do things? I don't want to redo the art for all resolutions. I have no idea how games with 2D art tackle that problem.

digital gull
#

does yield break wait for next frame before exitting the coroutine or does it in that same frame?

cosmic rain
digital gull
#

ty!

gray mural
#

Hey, I feel like this code is not entirely clean. Does anyone have a better solution?

chilly surge
#

Code looks fine by itself (you can invert newSetup != currSetup check to be a guard clause too)

#

Can't really give more suggestion without knowing what it's meant to do. Is it for some kind of step by step process?

leaden ice
digital gull
# leaden ice It ends it immediately but functionally what would the difference be? The point ...

For my use case I think it may make no difference, so I was just trying to understand it. Hypothethically I was thinking maybe it would make a difference in race conditions edge cases but I think its not relevant. Like I was thinking of something that would check if that coroutine was still running every frame how it would be affected by the difference of yield break waiting for 1 extra frame. But there are better ways to do that.

gray mural
#

I just don't like how these returns in the 2nd method look

#

I first thought about creating an IEnumerator and yield return these methods, but it wouldn't look fine, as would need to use a tuple (bool, Setup) to check for Current

leaden ice
chilly surge
#

If that's the case, it's honestly a perfect use case for async/await (or coroutine).

digital gull
gray mural
#

So that's the thing.
ExecuteKey
Is the suitable key binding selected for the Setup's process?
Yes? Return false and select this Setup
No? Return true and go check whether the key binding is suitable for the other Setups

hybrid orchid
#

Im curious if anyone here can find a flaw that I can’t. I have a script on all of the randomly generated foxes on my game called FoxBaseBehavior.cs. They also all use Navmesh path finding. However I’m not putting this in there because I don’t believe it’s related to my issue.

Everytime a fox enters a den all other foxes briefly disappear for a frame or two. Here’s the code snippet for how foxes handle entering dens


    private void DenEnter(List<object> list)
    {

        string denType = (string)list[0];
        if (_myStats.At.Name == denType)
        {
            ChooseRandomizedLocationFromPlace(denType, false);
            gameObject.SetActive(false);
        }

    }```

If you’re wondering why it’s a list basically I need to pass along extra information in that specific method for other areas of my game
Notably, I wonder if everytime one fox enters a den assigned to another fox, it triggers this on that fox as well
I just don’t know how it’s possible that could happen since this is a private method,so it correct me if I’m wrong: it would ONLY trigger for that specific fox game object
sullen portal
#

I think if private it would only work on the object the script is on. you can print objects in the list and maybe one is in there that shouldnt be? if so find out why.

leaden ice
#

Why not make an actual type?

#

anyway this is way too little information to know what's going on

#

we need a lot more context

#

but from this snippet there's a lot of questionable stuff going on.

hybrid orchid
leaden ice
#

instead of a random grab-bag List<object>

sullen portal
#

they said because the list contains other information. I think thats a pretty bad way to do it though. praetor approach is better.

hybrid orchid
#

Im using the send message syntax and that only lets you send one argument of information

leaden ice
#
public class DenInfo {
  DenType denType;
  int numberOfFoxes;
  Color foxColor;
}``` for example
hybrid orchid
#

We have a system similar to that, this is about sending information from one script to another

leaden ice
#

errors in this system could easily be the source of your problem

#

anyway in regards to the original problem, you'd have to share a lot more context and code.

hybrid orchid
#

True this is one of the first things I coded and I haven’t touched on it in almost a year, I should probably make it a event

sullen portal
#

I would resolve your bug then optimize into alternatives after. you dont want to create more issues amidst dealing with another.

civic nymph
#

My character is set up to move when I click to World Space. BUT if I click on UI they do not move. (That’s what SHOULD happen, and DOES while in Game mode)

When I’m in Simulator mode it does both at the same time. For example if I click on a button, it’s triggered AND I move to that location. If I keep clicking on any UI after this it will ONLY interact with the UI. When I click on World Space it still assumes I’m clicking on the UI for that one instance (Even if I click on a World Space). If I click on a World Space a second time I can move again.

My EventManager has all its needed components and I’ve restructured my Movement script to check for any synchronous functions. I really don’t know what else to do. Does anyone have any ideas how I can fix this?

#

please I'm begging for any kind of solution. I've been stuck on this for 2 days and nothing works

leaden ice
#

but basically - for a touch screen there's not really a "pointer" hovering over stuff. So if you're doing the EventSystem.current.IsPointerOverGameObject thing, it's not going to work

#

the solution here is to use the event system for everything and you get the UI blocking behavior for free

civic nymph
#

that's it?!

leaden ice
#

I kid you not

civic nymph
#

so something like? GameEvents.current.s_DoTheThing();

leaden ice
#

no

civic nymph
#

I got experiementing to do

#

thank you so much!

mossy gust
#

im wondering how i could make a movement system that doesnt use rigidbody for a platformer

gray mural
mossy gust
#

thanks!

spring creek
#

Call a sound manager which does it for you

arctic steeple
#

is pathway down ? I just checked pathway on unity and it's got 404

gray mural
arctic steeple
#

I guess because im dumb

civic nymph
#

I've started using the new Input system and it's saying the method is running twice when I give it an input

#
{
    public void move(InputAction.CallbackContext context)
    {
        //Debug.Log("Clicked on the WORLD");
        if (context.performed)
        {
            Debug.Log("Clicked on the WORLD " + context.phase);
        }
    }
}```
#

I don't get it

leaden ice
civic nymph
#

I get my player object

#

drag it here

leaden ice
civic nymph
#

just the one

leaden ice
#

You sure?

public class TestMovement : MonoBehaviour
{
    public void move(InputAction.CallbackContext context)
    {
        //Debug.Log("Clicked on the WORLD");
        if (context.performed)
        {
            Debug.Log($"Clicked on the WORLD {context.phase} on {this.gameObject.name}");
        }
    }
}```
civic nymph
#

let's see

#

(the scene is a mess while I get things sorted so just ignore all the disabled stuff)

leaden ice
# civic nymph

if you remove the move binding from here what happens?

civic nymph
#

in the callback context?

leaden ice
#

Remove the listener from the inespector

#

press the minus button here

civic nymph
#

that's what I figured you meant

#

ok

#

no more console alerts

leaden ice
#

ok that's certainly weird

#

Can you show a screenshot of your action?

#

I.e. from the input action asset?

civic nymph
#

maybe it's how I've set up my events

#

oh MAYBE

#

hold on

leaden ice
#

You might have some weird interaction or processor setup on it

#

like maybe you have the Press and Release interaction

civic nymph
leaden ice
#

pass through

#

set that to Button

civic nymph
#

yep that fixed it

#

wow

leaden ice
#

With Pass THrough on you'll get a performed event for any change in the control at all

civic nymph
#

thank you. this thing is giving me a headache while I learn it

leaden ice
#

Yeah it has a learning curve

civic nymph
#

do you mind helping me with something else that should be super basic?

leaden ice
civic nymph
#

oh ok

#

I'll go there

leaden ice
#

You can ask whatever you like but I can't commit to helping with it.

civic nymph
#

thanks again

cosmic geode
#

Hello!
Im trying to create a Codeless IAP button that purchases everything but i have to calculate its value at runtime.
After i get its value and i set its product ID to the ID that corresponds to its price i want to also update the text component that display its price.
I know i can update the value in the OnProductFetched listener but i was wondering if there is a way to do it outside the listener.

IAP Manager:

using TMPro;
using UnityEngine;
using UnityEngine.Purchasing;

public class IAPManager: MonoBehaviour
{
  [SerialzieField] CodelessIAPButton IAPButton;
  private float price;
  private float[] validPrices = { 9.99f, 14.99f, 19.99f, 24.99f, 29.99f, 34.99f, 39.99f, 44.99f, 49.99f, 54.99f, 59.99f, 64.99f, 69.99f, 74.99f };
  
  private void SetIAPButtonValue(int index)
  {
    price = validPrices[index];
    IAPButton.productID = $"purchase_everything_{price}usd";

    // Now after i set the id i would like to also update its text component so i was thinking of calling the .onProductFetched() but it doesnt work
  }

is there a way to atleast acces the product of the IAPButton after i set its ID?

mossy snow
#

what you're doing makes no sense. You'd create a product ID that represents purchasing everything and hook the button up to it. Unless you set up that product ID on the store side, you'll just get an invalid product id with what you're doing here. And since it's already set up on the store, you hook the button up to that product id. Hence the codeless part

spare island
#
        public static List<Transform> GetEntitiesInRange(Transform originTransform, float range, string entityLayer)
        {
            Collider[] colliders = new Collider[0];
            Physics.OverlapSphereNonAlloc(originTransform.position, range, colliders, LayerMask.GetMask(entityLayer));
            var entities = colliders.ToTransforms();

            // Remove self
            entities.Remove(originTransform);

            return entities;
        }

I'm not really sure why but when I walk my character into range of the AI it should be hit by the OverlapSphere but its not

#

Even if I walk right up to it

leaden ice
#

it can never hold anything

spare island
#

Ah

#

I kind of just assumed it made a new array anyway and assigned it

#

how am I supposed to know how much to allocate though

#

it really wants me to use the NonAlloc version, the IDE complains if I don't

leaden ice
# spare island how am I supposed to know how much to allocate though

This is the typical pattern:


static Collider[] resultsArray = new[10];

public static List<Transform> GetEntitiesInRange(Transform originTransform, float range, string entityLayer)
{
    int count = Physics.OverlapSphereNonAlloc(originTransform.position, range, resultsArray, LayerMask.GetMask(entityLayer));
    for (int i = 0; i < count; i++) {
        Debug.Log($"Overlapped {resultsArray[i]}");
    }```
#

The whole point of NonAlloc is to reuse an existing array

#

if you just create/allocate a brand spanking new array each time, it defeats the purpose of NonAlloc

spare island
#

oh it wants me to cache them

leaden ice
spare island
#

well it'd be kind of weird to cache this in my utility class

#

I guess I could put it in the parameter list of the method

lean sail
leaden ice
#

you should have this method return int and take in a results list or array

spare island
#

this is how i had it before

leaden ice
#

i.e., follow the same pattern as the nonalloc query

spare island
#

oops covered it

leaden ice
#
public static int GetEntitiesInRange(Transform originTransform, float range, string entityLayer, List<Transform> results)
{
    int count = Physics.OverlapSphereNonAlloc(originTransform.position, range, resultsArray, LayerMask.GetMask(entityLayer));
    int resultCount = count;
    for (int i = 0; i < count; i++) {
        var xForm = resultsArray[i].transform;
        if (xForm == originTransform) {
          resultCount -= 1;
          continue;
        }

        results.Add(xForm);
    }

    return resultCount;
}```
#

This is how I recommend you implement this

#

if you want to go the nonalloc route

#

if you don't mind allocating memory each time, just don't use nonalloc

#

You could also do this (clear the results array each time):

public static void GetEntitiesInRange(Transform originTransform, float range, string entityLayer, List<Transform> results)
{
    results.Clear();
    int count = Physics.OverlapSphereNonAlloc(originTransform.position, range, resultsArray, LayerMask.GetMask(entityLayer));
    for (int i = 0; i < count; i++) {
        var xForm = resultsArray[i].transform;
        if (xForm == originTransform) {
          continue;
        }

        results.Add(xForm);
    }
}```
spare island
leaden ice
#

I'm doing this because you wanted a List result

#

if you want an array result you can just pass the result array in, sure. But that won't let you do the thing where you ignore the "originTransform"

#

since arrays cannot be resized.

#

that being said - i highly recommend just using a layermask to do that

spare island
#

a layermask to do..?

leaden ice
#

to ignore the object you want to ignore

spare island
#

wouldn't that require a layer for every individual entity

leaden ice
#

no?

spare island
#

well all entities are on the same entity layer

leaden ice
#

It would ust require the things you're looking for to be on a different layer than the thing that is "performing the query"

#

remember I don't really understand your game

#

or know any context here

leaden ice
#

otherwise, use the list approach

spare island
#

The purpose is this is a method in an AI Utility class, its meant to return a list of the other "Entities" within a range of it (excluding itself)

leaden ice
#

alright well I've explained two different ways you can do that

spare island
#

so, for the static array, i guess its more efficient because im not creating/destroying an array everytime but just modifying an existing one?

#

because the other way i was doing it, i would be making an array and then it would be deallocated once GetEntitiesInRange is returned

#

(at least thats my understanding?)

leaden ice
#

which is wasteful

#

by the way, same with the list

#

that's why I suggested a version where the list is passed in as a parameter

spare island
#

im trying the second one now

spare island
# leaden ice that's why I suggested a version where the list is passed in as a parameter
        static readonly Collider[] resultsArray = new Collider[256]; // More efficient to reuse this array than to create a new one each time this method is called
        public static int GetEntitiesInRange(Transform originTransform, float range, string entityLayer, List<Transform> results)
        {
            results.Clear();
            int count = Physics.OverlapSphereNonAlloc(originTransform.position, range, resultsArray, LayerMask.GetMask(entityLayer));
            for (int i = 0; i < count; i++)
            {
                var xForm = resultsArray[i].transform;
                if (xForm == originTransform)
                {
                    continue;
                }

                results.Add(xForm);
            }
            return count;
        }

Usage:

            if (AIUtility.GetEntitiesInRange(_nav.transform, _sightRange, _entityLayer, _entitiesInRange) > 0)
            {
                SetTargetEntity(entitiesInRange: _entitiesInRange);
            }
            else
            {
                ClearTargetEntity();
            }
#

I am a little worried if keeping a static results array in the utility class is a bad idea

leaden ice
#

yeah if your goal there is to check for anything in range or not that works

But you could also use CheckSphere for that

#

which doesn't allocate anything at all

spare island
#

well because I'd have a bunch of entities calling this and it'd be constantly modifying this same array

leaden ice
#

Why is that a problem?

#

That's the point! Reuse is good.

spare island
#

It's probably not I just don't fully understand what im doing yet

#

So CheckSphere would be more efficient?

shell scarab
#

Anyone know how to get the PostProcess attribute working?

leaden ice
shell scarab
#

!code

tawny elkBOT
shell scarab
spare island
leaden ice
leaden ice
#

and that's where CheckSphere works

#

Oh but

#

I guess it doesn't

#

because of your whole "ignore myself" thing

spare island
#

It's setting the results array

#

CheckSphere returns a boolean which doesn't really help me

#

i need to know whats in the sphere

leaden ice
#

well in the case I was describing you wouldn't have needed to know

spare island
# leaden ice well in the case I was describing you wouldn't have needed to know

so does that memory thing mean i should be having these variables as static fields too in other methods?

        public static bool EntityInSight(Transform originTrans, Transform entityTrans, float sightRange)
        {
            Vector3 origin = originTrans.position;
            Vector3 direction = entityTrans.position - origin;
            _originalLayer = originTrans.gameObject.layer;

            originTrans.gameObject.layer = 2; // 2 = Ignore Raycast

            if (Physics.Raycast(origin, direction, out RaycastHit hit, direction.magnitude))
            {
                originTrans.gameObject.layer = _originalLayer;
                return hit.transform == entityTrans && direction.magnitude <= sightRange;
            }
            else
            {
                originTrans.gameObject.layer = _originalLayer;
                return false;
            }
        }
#

for example here the two Vector3s

#

or is this something already optimized by the compiler/GC?

leaden ice
#

it's a value type

#

it will just be allocated on the stack

#

there is no garbage collection involvement

spare island
#

tbh i've been programming for a while and still don't completely understand what 'the stack' is

leaden ice
#

the stack aka the callstack. It's how the program handles calling functions and then returning back where it was

#

it's uh...

#

maybe hard to explain if you haven't taken a systems programming class...

spare island
#

ive barely even taken a programming class

leaden ice
#

but the point is, local variables for value types are basically free.

spare island
#

i did take a C# OOP class but i didn't learn anything that i didn't already know

spare island
#

is there an easy way to tell value types apart from reference types? (i think thats the alternative to a value type?)

leaden ice
#

any type you look at in C# will be one of those two

spare island
#

and im assuming the difference between a struct and a class is that the allocation for a class is dynamic size-wise, but for a struct it will have to re-allocate everytime its modified?

leaden ice
#

no, it's not about the size being dynamic

#

classes also have a static size

#

it's about where it gets allocated and it's about how it gets passed as method paremeters/return types

#

if you do new MyStruct() it goes on the stack.
If you do new MyClass() it goes on the heap.

And structs get passed to and from methods by copying the value
Whereas classes get passed to and from methods by copying a reference to the object in heap memory.

#

the reason classes go in the heap is so that you can pass around references to them and be guaranteed that the reference will be valid

#

the stack is constantly getting written over whenever new functions are called and finished, so you can't guarantee an object in the stack will still be there later on.

spare island
#

so kind of like how registers work?

#

like when you call a subroutine and it stores the location of where you were when you called it in memory