#archived-code-general

1 messages · Page 139 of 1

ashen yoke
#

but then again there are massive titles out there that use singletons all over

#

main issue with them is you not being clairvoyant, if you knew 100% ahead of time what and how would look you could use static classes

#

while developing projects are volatile and have to adhere to things like solid because of it

compact spire
#

My project isn't big, just getting hung up on doing things "right", which is usually what kills my motivation.

ashen yoke
#

focus on solving that issue then

#

since you identified it

compact spire
#

I think I'll go with some direct references, it's only a handful of monobehaviors. Once more of the project has materialized I can sort out a solution to the structure that makes sense. I can't imagine that it's going to affect much downstream, so it should be a safe decision.

#

Thanks for the insight.

stark jacinth
#

!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.

stark jacinth
#

door script (shorter version): https://gdl.space/idopunuwed.cs

I'm making a door script where the door rotates (which works), but now I'm trying to get the handle to also rotate when you open the door. However, the door handle doesn't rotate -40 degrees on the y like I want it to.

gray mural
stark jacinth
#

wdym?

gray mural
#

I mean that handle should probably rotate by y axis

stark jacinth
#

oh sorry i meant y

gray mural
#

here?

front_handle.transform.rotation = Quaternion.Lerp(front_handle_endRotation, front_handle_startRotation, time);
back_handle.transform.rotation  = Quaternion.Lerp(back_handle_endRotation, back_handle_startRotation, time);
stark jacinth
#

yea

#

I set the end rotation and start rotation a couple of lines above

#

my front handle's rotation is set to (-180,0,0) by default and my back_handles rotation is set to (0,0,0) by default

#

I'm trying to get it to go down then back up when you open the door

#

by rotating -40 degrees on the y

gray mural
#

does it even rotate?

stark jacinth
#

yes the front handle goes from (-180,0,0) to like (-181,-0.something, -88)

#

I don't understand why it's rotating on the axis I don't want it to

gray mural
#

your script looks very strange for me

leaden ice
eager pewter
#

I want to do a simple test of Text Mesh Pro by simply displaying some white text to the screen. Keep in mind that I can only work with C# and not the Unity editor, and that everything will happen at runtime (for reasons I discussed earlier). Everything I can find online assumes the use of the editor, and I can't find a way to do this purely in C#.cs public void onGUI() { TextMeshProUGUI tmText = new TextMeshProUGUI(); tmText.color = Color.white; tmText.text = "Test Message"; //idk about positioning atm, we'll get there once it displays at all }

gray mural
#

why do you even rotate from endRotation to startRotation ?

stark jacinth
#

for Lerp

#

I want it to go from endRotation to my startRotation

#

in a certain amount of time

stark jacinth
leaden ice
#

You must create a GameObject and attach it with AddComponent

stark jacinth
#

arent you suppose to do Quaternion.Euler ?

#

or can you just do Quaternion

leaden ice
#

Your issue is you're expecting some specific Euler angle combination for your quaternions

leaden ice
leaden ice
stark jacinth
#

would Quaternion(new vector 3()) work?

leaden ice
#

No

#

You're not understanding

#

Quaternion.euler isn't the issue

#

It's you reading the results as Euler angles that is the issue

gray mural
#

@stark jacinth

float yOffset = 40f; // for example

// target rotation with offset added
targetRotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y + yOffset, transform.rotation.z);

// smoothly rotate from currect position to position with y offset
front_handle.transform.rotation = Quaternion.Lerp(front_handle.transform.rotation, targetRotation, rotationSpeed);
leaden ice
gray mural
#

what's wrong?

leaden ice
#

You are mixing up quaternion components with Euler angles

#

Very wrong

#

transform.rotation.y < very bad

gray mural
gray mural
#

oh, I have multiplied rotation

stark jacinth
#

alright so what would I use to rotate a gameobject from one point to another

gray mural
#

I haven't mentioned it

#
float yOffset = 40f; // for example

// target rotation with offset added
targetRotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y + yOffset, transform.rotation.z);

// smoothly rotate from currect position to position with y offset
front_handle.transform.rotation = Quaternion.Lerp(front_handle.transform.rotation, targetRotation, rotationSpeed);
#

it should be fine

leaden ice
#

Definitely won't be fine

gray mural
gray mural
buoyant crane
dusk apex
#

Neither is y and z

buoyant crane
#

you rarely ever want to access a Quaternion’s .x

#

or any of its specific components

stark jacinth
#

how else are you suppose to rotate objects though?

leaden ice
#

So much confusion has been introduced now

#

sigh

dusk apex
#

By not using the x, y and z components of quaternion.

stark jacinth
#

but isnt transform.rotation already a Quaternion

#

if I want to change that I would have to use another Quaternion

cosmic vector
#

Honestly. Confused why a code solution is being used instead of an animation solution.

dusk apex
#

They aren't Euler values

gray mural
#
float yOffset = 40f;

Vector3 targetEulerAngles = transform.rotation.eulerAngles;
targetEulerAngles.y += yOffset;

Quaternion targetRotation = Quaternion.Euler(targetEulerAngles);

front_handle.transform.rotation = Quaternion.Lerp(front_handle.transform.rotation, targetRotation, rotationSpeed);
gray mural
lean sail
#

also this lerp uses a = Lerp(a, b, t)

gray mural
#

I hate rotations.

gray mural
lean sail
#

meaning it will "speed up" in its rotation, unless its intended to have this exact effect

dusk apex
#

T should be a value that goes from 0 to 1

gray mural
dusk apex
#

c = Lerp(a, b, t)

gray mural
cosmic vector
#

rotation speed will approach zero the farther into the rotation it makes it

lean sail
#

visually it would look as if its speeds up, a is getting closer to b while increasing t

dusk apex
leaden ice
#

The t is constant in that solution

gray mural
leaden ice
#

So it will slow down

lean sail
#

ah, i believe the original code used time properly as T which is why i thought that 3rd param was still time

#

i understand now

dusk apex
#

Your formula was a = Lerp(a, b, constant t). Importance is a and t

lean sail
# gray mural what's that? it's formula I have used, yeah

a = lerp(a, b, t) is completely different
a is constantly changing, your lerp also should be increasing time instead rather than just bringing a closer to b at rotationSpeed which i presume is greater than 1

c = lerp(a, b, t) implies a is different from c, a is the start rotation

dusk apex
#

Google how to properly use lerp with Unity

lean sail
#

even the link u sent doesnt agree with what u wrote

buoyant crane
cosmic vector
# gray mural what's that? it's formula I have used, yeah

Easier to see problem with plain number lerp.

float a = 1;
float b = 2;
a = Mathf.Lerp(a, b, 0.1); // A = 1.1
a = Mathf.Lerp(a, b, 0.1); // A = 1.19
a = Mathf.Lerp(a, b, 0.1); // A = 1.271

As you can see the amount a changes each time lerp is called is a smaller amount. This is because the distance between a and b is becoming a smaller number, so the 0.1 is a smaller step between the two numbers.

What they are suggesting:

float a = 1;
float b = 2;
float c;
c = Mathf.Lerp(a, b, 0.1); // C = 1.1
c = Mathf.Lerp(a, b, 0.2); // C = 1.2
c = Mathf.Lerp(a, b, 0.3); // C = 1.3
buoyant crane
sweet linden
#

Guys had a quick doubt about Tilemaps. I'm using a Tilemap Collider 2D on my Tilemap and Circle Collider 2D on my player. But the collider don't seem to be working as my player can pass straight through the Tilemap. I'm moving my player by directly changing the transform. Is it something to do with that or something else?

gray mural
#

that was a really nice explanation

stark jacinth
#
 Quaternion startRotation = transform.rotation;
        Vector3 front_handleEulerAngles = front_handle.transform.rotation.eulerAngles;
        front_handleEulerAngles.y -= 40;
        Quaternion front_handle_endRotation = Quaternion.Euler(front_handleEulerAngles);
        Quaternion endRotation;
       
        

        if(ForwardAmount >= ForwardDirection) //if we set our Forward direction to a negative value the door always rotates a positive amount
        {
            endRotation = Quaternion.Euler(new Vector3(-90, 0, 0)); // Setting end rotation to -90 on the z

        }
        else 
        {
            endRotation = Quaternion.Euler(new Vector3(-90, 0, 0)); // Setting end rotation to -90 on the z
        }

        IsOpen = true;

        float time = 0;

        while (time < 1)
        {
            transform.rotation = Quaternion.Slerp(startRotation,endRotation, time); // Opening the door
            front_handle.transform.rotation = Quaternion.Lerp(front_handle.transform.rotation, front_handle_endRotation, time);
            yield return null; // Waiting a frame
            time += Time.deltaTime * speed; // Increasing the time incremently ; if we increase the speed, then the door will open faster
        }
#

this just rotates the door handle on the z

#

and not even by -40 degrees

gray mural
#
float time = 0f;
float yOffset = 40f;

Quaternion startRotation = front_handle.transform.rotation;

while (time < 1)
{
    Vector3 endEulerAngles = startRotation.eulerAngles;
    endEulerAngles.y += yOffset;

    Quaternion endRotation = Quaternion.Euler(targetEulerAngles);

    front_handle.transform.rotation = Quaternion.Lerp(startRotation, endRotation, time);

    time += Time.deltaTime * speed;    

    yield return null;
}
#

that should probably work for front_handle

dusk apex
#

It would be valid, assuming rotation speed is equal to time

gray mural
#
Quaternion.Lerp(startRotation, endRotation, time);
#

thx for reminding

stark jacinth
#

thats what I already wrote

#

just with different variable names

#

still rotates on the z

dusk apex
gray mural
#

actually that's your code...

endRotation = Quaternion.Euler(new Vector3(-90, 0, 0)); // Setting end rotation to -90 on the z
stark jacinth
#

thats for the door

#

which works

#

not the door handle

gray mural
#

yeah, show your code

stark jacinth
#
 Quaternion startRotation = transform.rotation;
        Vector3 front_handleEulerAngles = front_handle.transform.rotation.eulerAngles;
        front_handleEulerAngles.y += 40;
        Quaternion front_handle_endRotation = Quaternion.Euler(front_handleEulerAngles);
        Quaternion endRotation;

 IsOpen = true;

        float time = 0;

        while (time < 1)
        {
            transform.rotation = Quaternion.Slerp(startRotation,endRotation, time); // Opening the door
            front_handle.transform.rotation = Quaternion.Lerp(front_handle.transform.rotation, front_handle_endRotation, time);
            yield return null; // Waiting a frame
            time += Time.deltaTime * speed; // Increasing the time incremently ; if we increase the speed, then the door will open faster
        }
stark jacinth
gray mural
#

no rotation happens at all

stark jacinth
#

I have a player action script which activates it

#

when I press e

gray mural
#
startRotation == endRotation == transform.rotation
stark jacinth
#

how I altered my endRotation

#

by changing it on the y by 40 degrees

gray mural
#
Quaternion startRotation = transform.rotation;
Quaternion endRotation = Quaternion.Euler(StartRotation);
stark jacinth
#
 Vector3 front_handleEulerAngles = front_handle.transform.rotation.eulerAngles;
        front_handleEulerAngles.y += 40;
        Quaternion front_handle_endRotation = Quaternion.Euler(front_handleEulerAngles);
gray mural
#

that's full code you have sent

stark jacinth
#

I mean my door rotation

stark jacinth
#

its literally in the code I sent

gray mural
#

oh

#

I see

#

that's in DoRotationOpen

#

I was looking on DoRotationClose()

stark jacinth
#

Yea, dont worry about doRotationClose()

#

thats why I didnt send my full code before

cosmic vector
#

ngl the variable naming is only slightly confusing. startRotation and StartRotation

stark jacinth
#

yea, sorry about that I kind of rushed to write the code

gray mural
#

also this doesn't make lots of sense:

if (ForwardAmount >= ForwardDirection)
{
    endRotation = Quaternion.Euler(new Vector3(-90, 0, 0));

}
else 
{
    endRotation = Quaternion.Euler(new Vector3(-90, 0, 0));
}
stark jacinth
#

I was using dot product to have the door open facing away from the player at all times

#

but then I decided not to so I just left the else and made their rotation the same

gray mural
#
front_handle.transform.rotation = Quaternion.Lerp(front_handle.transform.rotation, front_handle_endRotation, time);
#

you should assing startRotation

earnest gazelle
#

When I change a sprite texture for example in photoshop in editor (play mode) and back to unity, the main material (world) changes to a flat color!
or change material properties and then press ctrl + z
Every changes in the project, import an asset, etc.

gray mural
#
frontHandleStartRot = front_handle.transform.rotation;
#

and then you use it

gray mural
#

and that's how your rotation should actually work

earnest gazelle
stark jacinth
#

there has to be some conditions that we don't know about in the documentation

#

because obviously eulerAngles.y does not work for the y for me

cosmic vector
#

Haven't really read your code. By any chance should you be using local rotation instead of rotation? So you're rotating relative to the door and not relative to the world?

gray mural
#

debug it

earnest gazelle
#

I have implemented a custom shader but what is the relation between this shader/material and changes in the project in play mode :/
My shader sets a buffer at the beginning. It seems it resets when modifying the project in play mode!

  var buffer = new ComputeBuffer(tiles.Length, size, ComputeBufferType.Default);
            buffer.SetData(tiles);
            _voxelMaterial.SetBuffer(TextureDataID, buffer);
gray mural
#

do it in while loop @stark jacinth

print($"{front_handle.transform.rotation}; {front_handle_endRotation}; {time}");
cosmic vector
#

Pretty sure just changing it to use localRotation will get it to work.

stark jacinth
cosmic vector
#

Well. Since it's a child object. And the parent is rotating. You'll need to work with localRotation or it'll be rotating ignoring the rotation of the parent. Without seeing what it is actually doing idk

tawny elkBOT
#

🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.

📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!

💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.

For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting

cosmic vector
#

Very unlikely this is a unity bug.

gray mural
mossy plover
#

anyone knows why my trees act like that?

#
        if (go.TryGetComponent<Rigidbody>(out Rigidbody rb))
        {
            go.GetComponent<Rigidbody>().AddTorque(transform.forward * 5, ForceMode.Impulse);
        }
#

this is code giving torque force

rigid island
mossy plover
#

to fall like in real life

rigid island
#

normally a tree doesn't rotate

mossy plover
#

without giving force it stay in place

mossy shard
rigid island
#

but not rotation

rigid island
#

also GetComponent<Rigidbody>() is redundant

#

you already stored the component in rb when component is found in TryGet

mossy plover
#

okay thanks

lean sail
#

or deter it at least, since it still can rotate

rigid island
#

hmm I'd do
AddRelativeForce or AddForceAtPosition on the axe hit would be better

lean sail
#

i think the issue mainly is just the trees collider is like a cylinder though, at least thats what it looks like

rigid island
#

ofc it's always a game, doo whatever looks /feels best

#

doesn't have to be totally real

mossy plover
mossy shard
rigid island
#

insta-boxes

lean sail
cosmic vector
#

If the goal is to not have rotations at all then you could probably just lock the y rotation on the rigid body altogether.

mossy shard
#

^

lean sail
#

they probably do not want it locked, otherwise u end up with really weird cases where your tree just doesnt move when its supposed to

mossy shard
#

and often times it looks goofy for a tree to rotate when falling

lean sail
#

im talking about before it lands completely. Once it falls, it doesnt matter if its locked or not

mossy shard
#

ye exactly

#

it would look a little more natural then to give boundries to y rotation

#

TBH

lean sail
#

locking a rotation looks more natural?

#

they'll end up with cases of it landed on another tree at the edge, box collider cant rotate on y -> its stuck when it shouldnt be

rigid island
#

any rotation doesn't look natural, maybe on impact if it gets to roll

#

trees dont rotate generally when cut down

eager pewter
#

If I do GameObject example = new GameObject(); at a local scope, will the object be deleted by the garbage collector at the end of the scope?

mossy plover
#

no

mossy shard
mossy plover
#

i think

mossy shard
#

when falling

#

you are talking like i am stoping the x rotation

lean sail
#

also itll be given a transform by default

eager pewter
#

fine by me!

#

also great

gray mural
#

!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.

gray mural
#

I have even done Coroutine to avoid it.

#

I think smth is just not update quick enough

#

I probably should ForceMeshUpdate before yield break

_textComponent.ForceMeshUpdate();

yield break;
#

it doesn't work actually

#

that's what happens

obsidian trench
#

is there any function that allows me to run a function for a fixed duration of time?

prime sinew
obsidian trench
#

wfs?

prime sinew
#

could use a coroutine

gray mural
prime sinew
#

or a simple float based timer, a bool, and the Update

obsidian trench
prime sinew
#

look into coroutines

obsidian trench
prime sinew
#

what yourfriend is suggesting isn't quite what you're after

#

well...

#

what you want is really just a bool that flips after a timer

gray mural
#

you use coroutine and break it after some period of time

prime sinew
#

up to you how you want to make the timer

#

float, or coroutine

#

or yeah what they said

obsidian trench
prime sinew
#

just look into coroutines, it'll do what you want

obsidian trench
#

yessir

eager pewter
# eager pewter I want to do a simple test of Text Mesh Pro by simply displaying some white text...

(See this message for context)

Any idea what's up with this?```cs
screenParent = new GameObject();
screenParent.transform.parent = GameObject.Find("Menu").transform;

TextMeshProUGUI textTM;

GameObject o = new GameObject();
o.transform.parent = screenArrayParent.transform;
o.transform.localPosition = new Vector3(100, 40, 0);
o.AddComponent<CanvasRenderer>();

textTM = o.AddComponent<TextMeshProUGUI>();
textTM.color = Color.white;
textTM.fontSize = characterSize;

//... later in OnGUI() ...

textTM.text = "Hello!";```It displays nothing

gray mural
gray mural
#

not the best name actually

eager pewter
gray mural
lean sail
gray mural
lean sail
gray mural
#

does it happen thanks to this line?

_instance = obj.AddComponent<PlayersManager>();
lean sail
#

no, u can just do new GameObject() and it will spawn with a transform

gray mural
#

I thought that doesn't work so

cosmic vector
#

new() is just short hand for new GameObject() btw

lean sail
cosmic vector
#

Well I finally got this stupid marching cubes thing to work... So I'm going to bed. Cya o/

eager pewter
# gray mural what is not displayed?

...the text. My whole goal rn is basically to print some text to the screen. Look at my original message I linked for more context. This here was my new code based on feedback on the old one

lethal plank
#

guys i need help
my project keep crashing
it show "failed to build mask for shadow culler" error and then crash
help

gray mural
#

wait, what's with your OnGUI?

public void onGUI()
{
    TextMeshProUGUI tmText = new TextMeshProUGUI();
    tmText.color = Color.white;
    tmText.text = "Test Message";
    //idk about positioning atm, we'll get there once it displays at all
}
#

why from small letter?

lean sail
opaque lodge
lean sail
eager pewter
#

that said...

#

I can confirm that the objects exist

#

and that they do have a TextMeshProUGUI component

lean sail
#

are you setting its parent to be a canvas

gray mural
eager pewter
#

What you see here is (parent's parent | parent | object | text content (empty))

eager pewter
eager pewter
#

besides, I've been using screenshots this whole time. Just didn't feel like waiting a minute for this one simple pic

lean sail
#

without being able to use the editor, this really is just a lot harder. you should try to print out though i guess if it has a transform or recttransform

eager pewter
#

Main is the parent of TextTerminalParent, which is the parent of TextTerminalCell[row;col which has a TextMeshProUGUI component containing an empty string

#

Ok, here it is w/ some text inside the components

lean sail
#

so uh is that working?

#

i think u said it was supposed to display hello

eager pewter
#

correct

#

but it isn't

lean sail
#

can you show the entire code with a code site?

eager pewter
#

sure

lean sail
#

or whatever is completely relevant, because from before your OnGUI was questionable

eager pewter
tiny reef
#

How can I efficiently change the color of tiles in a tilemap?

Im making a physics simulation so I have a very big tilemap (around 1000x1000 tiles)
And each tile should have a specific color based on some value changing every frame

lean sail
#

unless this is called by you in some other code, I would add debugs to see whats actually running... but idk how u would without the editor

#

maybe print to file lol

lean sail
eager pewter
#

tbf, that function is actually runGUI() in my code, and is actually called by cs public void OnGUI() { if (terminal.active) { terminal.runGUI(); } }I just changed it to OnGUI in the hastebin because I wasn't including the other file

lean sail
#

ah i understand

tiny reef
#

Maybe pass an array of all the colors to a shader?

lean sail
#

i dont know too much about tilemap or 2d in general sorry, but maybe you're looking for a shader to calculate this for you based on the value

lean sail
eager pewter
#

I may have an update... (posting this pic for my own reference)

tiny reef
#

Well all values are changing every frame
So I need to update the color as well haha

#

The values are just a float which the color depends on

lean sail
lean sail
lean sail
tiny reef
marble spindle
#

I wonder how tower defense games go with that "attack strongest" first or last enemy what kind of collection would be best for that much sorting

lean sail
tiny reef
#

Yeah

#

For every tile a value

#

It’s like a hight value
Im making a 2d wave equation simulation

#

Should’ve said that at the start probably haha

lean sail
#

could be valuable looking at those youtube videos about rendering massive amounts of objects. I dont know too much else about this

tiny reef
#

Yup thanks

next sparrow
#

Hello, I'm trying to pin a model bones to another model bones

#

targetRenderer.bones = sourceRenderer.bones.Where(b => targetRenderer.bones.Any(t => t.name == b.name)).ToArray();

#

I'm using the current code

#

But it seems like when the child model has some bones the parent doesn't have causes some issue and the child model simply doesn't display anymore.

#

It's working fine for 90% of my models but for the 10% left, they just don't show up after pinning and after checking, I'm assumig it's because those models have extra bones? Not too sure.

#

Would anybody have an idea?

#

Reading the code I sent, it does appear to destroy the child bones using the parent bones so that does explain the problem. But I'm not sure how to fix the issue. I'd need to keep the child extra bones while still pinning the matching bones.

#

OR I might just remove the extra bones from the child actually... That might seem like a faster solution

next sparrow
#

Well, that fixed the issue but losing those extra bones also cost me some blend shapes... Isn't there anothert way to pin bones together while keeping extra bones by any chances?

next sparrow
#

OK I've managed to keep the extra bones by writing 2 foreach loop instead. If I find a matching bones, I pin it otherwise I keep the child bones. But for some reasons, the child bones doesn't follow the parent movement anymore.

#

Despite still being a child in the hierarchy

gray mural
#

Why I cannot see some fields while debugging?

#

it's not shown

wooden cove
#

can I leverage unity's navmesh pathfinder on a grid system or do I just need to make my own (A* algo)

dusk apex
gray mural
#

when hovering

dusk apex
#

What do you mean by that? Text component index would be the field

#

You mean value?

#

Definition?

dusk apex
#

Implementation?

#

Right, so value

gray mural
#

when you hover value in debugging - you can see it

#

but it doesn't work with lots of my values

#

how does it even happen?

dusk apex
#

If you're debugging with your ide, you should be shown a details pane with all values of variables in vs.

gray mural
#

it should apper when howering

#

and then you select visualiser

#

I think it's called so

#

but I cannot see those values

#

do I just have unlucky day?

dusk apex
#

Well, the difference between the two images you've shown above is that last line is a field and text is a property

gray mural
#

oh, you have sent a link too.

gray mural
#

I actually do have problems with attention

warm shadow
#

I really need help. I have tried to make a system that detects if a UI object is partly out of the screen, so I can move it inside, but no matter what I try it doesn't work. I am using an aspect ratio of 16:9 as I'm developing for mobile. Here is the code from my current attempt:

#
public void CreatePopUp(string _translatedSentence, Vector3 popUpPosition)
{
    currentPupUp = Instantiate(popUpUIPrefab, canvas.transform);

    currentPupUp.transform.position = popUpPosition;
    Rect popUpRect = currentPupUp.transform.GetComponent<RectTransform>().rect;

    //Calcualte if flip image
    if (RectOverlap(currentPupUp.transform.GetComponent<RectTransform>(), borders[0])) // TOP
    {
        currentPupUp.transform.rotation = Quaternion.Euler(180, 180, 0);
        print("TOP");
    }
    else if (RectOverlap(currentPupUp.transform.GetComponent<RectTransform>(), borders[1])) // BOTTOM
    {
        currentPupUp.transform.rotation = Quaternion.Euler(0, 180, 0);
        print("BOTTOM");
    }
    else if (RectOverlap(currentPupUp.transform.GetComponent<RectTransform>(), borders[2])) // RIGHT
    {
        currentPupUp.transform.rotation = Quaternion.Euler(0, 0, 0);
        print("RIGHT");
    }
    else if (RectOverlap(currentPupUp.transform.GetComponent<RectTransform>(), borders[3])) // LEFT
    {
        currentPupUp.transform.rotation = Quaternion.Euler(0, 180, 0);
        print("LEFT");
    }

    currentPupUp.transform.GetChild(0).rotation = Quaternion.Euler(0, 0, 0);

    currentPupUp.GetComponentInChildren<TMP_Text>().text = _translatedSentence;
    isShown = true;
}
#

private bool RectOverlap(RectTransform firstRect, RectTransform secondRect)
{
    if (firstRect.position.x + firstRect.rect.width * 0.5f < secondRect.position.x - secondRect.rect.width * 0.5f)
    {
        return false;
    }
    if (secondRect.position.x + secondRect.rect.width * 0.5f < firstRect.position.x - firstRect.rect.width * 0.5f)
    {
        return false;
    }
    if (firstRect.position.y + firstRect.rect.height * 0.5f < secondRect.position.y - secondRect.rect.height * 0.5f)
    {
        return false;
    }
    if (secondRect.position.y + secondRect.rect.height * 0.5f < firstRect.position.y - firstRect.rect.height * 0.5f)
    {
        return false;
    }
    return true;
}
pearl cape
placid island
#

!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.

placid island
#

I don't understand why I should add the buffer to IList<ArraySegment<byte>> every time and remove it every time

#

If possible, please tell me how this overload of BeginReceive works, I'm really confused about it

#

Also, if a part of data arrives when another part of data is processing, will the prior data be overwritten? There is only one buffer and that list is just many reference to the buffer

quartz folio
placid island
#

! sorry

gray mural
# quartz folio

this windows appears every time I do it, regardless what value I am hovering

gray mural
#

Also I cannot see values that I don't assign

#
int firstCharacterIndex = _textComponent.textInfo.lineInfo[_textComponent.textInfo.lineCount - 1].firstCharacterIndex;

string lastLine = text[firstCharacterIndex..];

_textComponent.text = text[..firstCharacterIndex];
steady moat
#

That means that either, you did not save correctly, Visual Studio has a bug or you are not in the correct scope.

#

Restarting Computer sometimes solve the issue for me.

thorn iron
#

Hey! Hi! Could someone help me display a dialogue system?

latent latch
# warm shadow I really need help. I have tried to make a system that detects if a UI object is...
private void Update()
{
        //Pivot anchor left for tooltip prefab
        
        //Mouse Pointer
        Vector2 pivot = inputSystem.point.action.ReadValue<Vector2>();
        //Tooltip is displayed on right side of pivot; flip it over to left side if there is not enough screen space
        if (pivot.x + toolTipRectTransform.rect.width > canvasWidth)
        {
            pivot.x -= toolTipRectTransform.rect.width;
        }
        //Tooltip is displayed mid length from the pivot; shift it downward if it's too far up offscreen
        if (pivot.y + toolTipRectTransform.rect.height / 2 > canvasHeight)
        {
            pivot.y -= pivot.y + toolTipRectTransform.rect.height / 2 - canvasHeight;
        }
        //Shift it upward if it's too far down offscreen
        else if (pivot.y - toolTipRectTransform.rect.height / 2 < 0)
        {
            pivot.y -= pivot.y - toolTipRectTransform.rect.height / 2;
        }
        //Do we need a case for if the tooltip is too large to be displayed, both up and downward?
        transform.position = pivot;
}```

Worked on this quite a while ago for my item tooltips that readjusted if it went off the canvas. Seemed to work ok but didn't test it that much.
thorn iron
thorn iron
latent latch
#

Probably show what* you've tried so far to give an idea what it's supposed to do

thorn iron
thorn iron
opaque lodge
#

Assume that I have a player with a model that consists of 2 spheres - the head and the body, the player exists as a whole - with a capsule collider in the parent - when is still living. I want to make it so that when the player dies, his head and body just disjoin and just start rolling around. Is there any approach to that?

warm shadow
thorn iron
warm shadow
# thorn iron Oh xd

yeah, i finished it, only skipping the last episode, and then i havn't gotten back into it yet, but i do have plans on it

thorn iron
latent latch
#

and detach the gameobjects if needed

jaunty needle
#

Why is this not working? I'm trying to save and load the position of messages:

    {

        phoneController = FindObjectOfType<PhoneController>();
        rbMessages = phoneController.rbMessages;
    }

    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            SaveMessagesPos();
        }

        if(Input.GetKeyDown(KeyCode.LeftShift))
        {
            LoadMessagesPos();
        }
    }

    public void SaveMessagesPos()
    {
        //when this function is called, store the position of the messages when the scene was left

        for(int i = 0; i < rbMessages.Length; i++)
        {
            positionMessages.Add(rbMessages[i].transform);
        }
    }

    public void LoadMessagesPos()
    {
        for(int i = 0; i < rbMessages.Length; i++)
        {
            rbMessages[i].transform.position = positionMessages[i].position;
        }
    }
#

When I try to load them it doesn't do it but the positions are saved in the list

flat aurora
#

Hey all. I am trying to use the Runtime OBJ Importer (from the Asset store) to dynamically load objects into my scene. These objects are supposed to come from an external folder (a folder inside the build folder) as I want to be able to add files after the project has been built. In the editor, this all works fine. However, in the actual build, nothing is showing up.

At the moment, I am testing with the sample scene provided, and with debug statements I've found that the line "loadedObject = ... " is where it is going wrong

        if(GUI.Button(new Rect(256, 32, 64, 32), "Load File"))
        {
            File.AppendAllText(logFilePath, objPath);

            //file path
            if (!File.Exists(objPath))
            {
                error = "File doesn't exist.";
                File.AppendAllText(logFilePath, error);
            }else{
                if(loadedObject != null)            
                    Destroy(loadedObject);

                loadedObject = new OBJLoader().Load(objPath);
                error = string.Empty;
            }
        }

Does anyone have experience with this asset and can help me?

heady iris
#

the log file path is not located inside the built game

#

it's some other (platform dependent) path

flat aurora
#

the logfilepath is just for debugging, because i wanted to check the filepath was correct and such

heady iris
#

oh, I see

#

I misread that as joining the paths or something

flat aurora
#

Ah no its just for debugging, needed to check the filepath. But the issue is that everything works fine in the editor, but nothing is loading in the built application itself

heady iris
#

perhaps loadedObject will have some information about the problem

#

i don't know what the type is

gray mural
#

I still have troubles with those values that I cannot see

#

I can see firstCharacterIndex here, but not any of _textComponent (TMP_Text) values

int firstCharacterIndex = _textComponent.textInfo.lineInfo[_textComponent.textInfo.lineCount - 1].firstCharacterIndex;
#

it makes debugging awful.

steady moat
gray mural
#

so I can now do it just like this:

var foo = _textComponent;
steady moat
#

On the break point

#

There is other option

#

You use the action one and do {_textComponent.name}

gray mural
steady moat
#

If I remeber correctly

fresh cosmos
#

whats the difference between Task.Yield() and Task.Delay(0) in relation to unity?

#

if i just want to wait to check the progress of loading something in an async, which should i use in a while loop?
i wouldnt need to check the progress more times than there are frames so if yield is shorter then i could use delay with a very small value

steady moat
#

Inherently, the progress is something you define.

#

You add function calls inside your task to say what the current progress is.

#

Then you can read it from there.

fresh cosmos
#

well this is loading scenes which has a built in progress

steady moat
#

If it is about loading scene, you should use the Scene API.

fresh cosmos
#

well yes, im making an extension to make mutli scene workflow easier, so i have a static class that has async methods to load in collections of scenes with a single line of code from the user, so i need to also relay the progress to the user. and i dont need to do that more often than each frame which brings me to the question i had

#

how often will the async continue in relation to unity with the two options : Task.Yield() and Task.Delay(0)

steady moat
spark flower
#

hey im trying to cast a ray to check if it connects with a solid object but it doesnt work as intended, is the direction calculation correct?
!Physics.Raycast(transform.position, (target.transform.position - transform.position).normalized, coneRange, solidLayer)

steady moat
#

You can use Debug.DrawLine or Debug.DrawRay to visualize the ray.

spark flower
#

ok

#

i think problem was the ray was too long and collided with solid objects behind the target...

#

yes that was the problem, everything works fine now

gray mural
warm stratus
#

Hey, which encryption method is the fastest? (i don t wan t the best security)

https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aes?view=net-7.0

StringBuilder result = new StringBuilder(_dataToEncrypt.Length);

        for (int i = 0; i < _dataToEncrypt.Length; i++)
        {
            result.Append((char)(_dataToEncrypt[i] ^ encryptionKey[i % encryptionKey.Length]));
        }
    
        return result.ToString();
steady moat
#

Ask yourself if you truly need it.

warm stratus
steady moat
warm stratus
steady moat
#

So, a solo game ?

warm stratus
#

but you can share levels

steady moat
#

It is fundamentally solo ?

#

Do you make the player play online.

warm stratus
#

yes it is

#

solo

steady moat
#

Then, you cannot prevent cheating.

warm stratus
#

but i wan t to discourage for cheating

steady moat
#

Which means, that it does not matter.

warm stratus
#

i wan t to make cheating not extremelt easy

steady moat
#

Why ?

#

The player has no advantage over anybody with cheating in solo game.

warm stratus
#

beceause you will be able to have more obstacles to add in the levels

#

that you can share

steady moat
#

I do not understand.

dusk apex
#

Just hide any saved data. Else if someone's going to actually decompile your code, there's little you can do about it unless data is stored server side.

steady moat
#

Cheating, only matters in Online game.

#

And even there.

#

Some type of Online game can be fine with cheats.

warm stratus
#

like imagine my game is geometry dash but to create levels with spikes you have to be level 10 i don t wan t random guys having instant infinity level to do that do you understand?

steady moat
#

Except, screwing up your progression system.

dusk apex
#

If they're willing to lookup exploits for your game and if your game is popular enough, they'll be able to pull it off regardless of the extra mediocre layer.

warm stratus
steady moat
#

If you truly want to prevent cheating a level creator that limits the amount of object a player can place, you will need to have a server that handle it.

steady moat
warm stratus
#

ok so are the files on android hidden?

dusk apex
#

Most people do not know how to navigate to the persistent data path or even know it's location - off the top of their head.

steady moat
warm stratus
#

that mean it s so hard to cheat

steady moat
#

However, any layer you gonna add on the client side will have no effect what so ever.

warm stratus
#

where are the files stored?

dusk apex
#

Google

warm stratus
#

ok i think i know what to do, i put a random file extension and that s it

#

without encryption

fervent furnace
#

split the data into multiple file and increase the io time

warm stratus
#

ok thks for that i won t encrypt the datas

dusk apex
#

It'll require more effort on their part and yours UnityChanLOL But if they're really determined, they'll be able to Google it immediately and you'd just have longer file io segmented read write etc

#

Assuming your game becomes ultra popular and have a large player base

mental orchid
#

How do you use LoadAssetFromFileAsync? If I just call it I would expect it to eventually be completed right? Or is there something special I need to do to get it to start loading

#

I'm having this issue where I'm calling LoadAssetFromFileAsync but its just not progressing/completing at all

leaden ice
mental orchid
#

Hm yea it's just not completing at all

#

Any idea how to debug this?

#

VS crashes when I try to debug and look at the request

leaden ice
#

can you link the documentation or this function?

#

I don't actually remember where it's from

leaden ice
#

What does your code look like

mental orchid
#

I initially tried just putting all the requests into a list and doing a busy wait for completion in a coroutine

leaden ice
#

you can just yield return the handle it gives you back (as per the example)

mental orchid
#

that's also not working

#

which is why I'm wondering how I can debug this at all

leaden ice
#

Can you show your code?

mental orchid
#

hold on I just made my VS crash by trying to inspect the request lol

#
public IEnumerator LoadDependenciesAsync(string assetBundleName, List<AssetBundleCreateRequest> writeRequestsTo)
        {
            string[] dependencyNames = Manifest.GetAllDependencies(assetBundleName);

            HashSet<string> loadedAssetBundleNames = new(AssetBundle.GetAllLoadedAssetBundles().ToList().ConvertAll(x => x.name));

            foreach (string dependency in dependencyNames)
            {
                if (loadedAssetBundleNames.Contains(dependency))
                {
                    continue;
                }

                AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(Path.Combine(Application.streamingAssetsPath, dependency));
                writeRequestsTo.Add(request);
                yield return request;
            }
        }
#

this is what it currently is after I gave up on the busy waiting

#

the caller of this function provides the list reference to write the requests to, which i'm still reading for a loading bar

#

although i guess now that i'm doing a yield return instead of a busy wait the loading bar doesn't actually move anymore

#

Here's what I was originally doing

public List<AssetBundleCreateRequest> LoadDependenciesAsync(string assetBundleName)
        {
            string[] dependencyNames = Manifest.GetAllDependencies(assetBundleName);

            HashSet<string> loadedAssetBundleNames = new(AssetBundle.GetAllLoadedAssetBundles().ToList().ConvertAll(x => x.name));
            return dependencyNames.Select(
                x => loadedAssetBundleNames.Contains(x)
                    ? null
                    : AssetBundle.LoadFromFileAsync(Path.Combine(Application.streamingAssetsPath, x)))
                .Where(x => x != null)
                .ToList();
        }
#

but in either case the AssetBundleCreateRequest is not completing, which I can't debug because it crashes my VS
it's not throwing any exceptions either

late mango
#

Hey guys, I'm trying to get the world rotation (in euler angles) from my game object. The first time it works, starts at 0 and is then set to -90. But the second time, it starts to 0 and not -90 like it should, any idea why? I've already tried some workarounds but none seems to work

wooden cove
#

If I have a grid based movement system, can I use the navmesh from unity? or would it be better to write a custom pathfinding solution?
I need to call a move function between each tile, to animate the move correctly, and I'm not sure I can do it with the navmesh system

leaden ice
late mango
#

I play an animation that makes an object turn to -90 degrees

#

It's inside an empty parent and at the end of the animation I set a new z rotation to the parent so the anim will start from the new position

gray mural
#

I have mentioned that everything executed even when line above has not executed yet. How do I avoid it?

thin hollow
#

Anybody encountered an issue when a script changes a variable in another game object, but it doesn't registers by Unity as changed (getting bolded on a game object), and upon hitting play it reverts to the default state? I'm making a node path system and I try the nodes to automatically set connections with each other when I hook them up in the editor. One of them works funny and looks like this, becoming like the second picture during the playtesting:

leaden ice
thin hollow
#

For comparison, a node that works correctly has the "prev point" variable properly bolded out like it should be:

steady moat
thin hollow
thin hollow
leaden ice
#

that's just one function

dusk apex
#

Maybe show your code if it's code related

thin hollow
#

I'm unsufe if it'll fit in Discord, but sure, a sec

leaden ice
#

!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.

leaden ice
#

@thin hollow ^

steady moat
#

// Notice that if the call to RecordPrefabInstancePropertyModifications is not present,
// all changes to scale will be lost when saving the Scene, and reopening the Scene
// would revert the scale back to its previous value.

thin hollow
steady moat
#

Do not do that...

#

Use OnValidate at worst.

thin hollow
#

OnValidate is called only once, no?

steady moat
#

Each time you make a modification on the inspector of the object.

thin hollow
#

Oh, yes, that's good to know. I thought I read somewhere that it's called only when you load the prefab for a first time or when opening a scene

steady moat
#

Anyway, OnDrawGizmos is definitly not the best way to achieve what you want.

gray mural
#

Hello, just wanted to ask how that's even possible
_textComponent is TMP_Text, textComponentIndex is currect textComponent's index

print($"textComponent: {textComponentIndex}; lineCount: {_textComponent.textInfo.lineCount}; text: {_textComponent.text}");
thin hollow
#

and that for changing something in editor you need to assign [ExecuteInEditor], which immediately causes a lot of issues if you forget to add checks that it isn't playmode.

steady moat
#

And I see no mention of RecordPrefabInstancePropertyModifications

thin hollow
gray mural
#

It doesn't make sense for me

steady moat
gray mural
#

and that's issue I get every 5th time

gray mural
steady moat
#

and when it gets refresh

steady moat
gray mural
#

I change _textComponent when lineCount > _textComponentLineCount (2 in our case). It's 3 in this case, but sometimes 17 or more

dusk apex
#

Maybe you've concatenated a bunch of new line characters 🤷‍♂️

gray mural
dusk apex
#

Also, check the docs

steady moat
dusk apex
simple egret
#

Tip if you didn't know, you can foreach over a string and it'll yield some char you can print out and even cast to int to get their index in the charset (useful for invisible or zero width chars)

gray mural
steady moat
dusk apex
gray mural
steady moat
#

Right Click -> Go To Implementation?

#

Something like that.

gray mural
#

it goes to TMP_TextInfo class

steady moat
#

Yeah, then read code

#

What is updating lineCount ?

gray mural
#

it's updated just to 0 when cleared

steady moat
#

Who owns lineCount ?

gray mural
steady moat
gray mural
#

it's TMP_Text.textInfo.lineCount

steady moat
#

Alright, could it be possible that the field is exposed ?

gray mural
gray mural
steady moat
#

Then, find who modify the values.

eager yacht
thin hollow
steady moat
#

In other words, you are not doing it the intended way.

thin hollow
#

But I marked the variable as serialized

gray mural
steady moat
eager yacht
#

I showed where it is edited

#

Three methods

gray mural
thin hollow
gray mural
#

I cannot find it with Ctrl + F

eager yacht
#

Bro

gray mural
#

just lineInfo is edited

eager yacht
steady moat
gray mural
#

it is not found with Ctrl + F

eager yacht
#

In the first two functions I gave you. In the clear it sets it to zero.

simple egret
#

You're probably navigating through decompiled code, reference and usage metrics might be inaccurate

thin hollow
#

by accident

steady moat
gray mural
#

that's the only place

eager yacht
#

I have no idea what that is supposed to tell me. Every time the text's mesh generates, it calculates the line count

fresh cosmos
#

how can i throw an exception that can highlight an Object as context in the project files like how debug.log() can?

gray mural
fresh cosmos
eager yacht
#

Sure does calculate it in a loop and assigns it after

steady moat
scarlet viper
#

how to delete current .material and make the renderer use its .sharedmaterial instead?

gray mural
fresh cosmos
eager yacht
#

Again, in the first two functions I gave you.

steady moat
#

There is EditorGUIUtility.PingObject();

fresh cosmos
#

ah, ok so i can add that to an exception then

#

thaknu

thick terrace
gray mural
eager yacht
#

Both of them

gray mural
gray mural
#

it's partial class

#
public partial class TextMeshProUGUI : TMP_Text, ILayoutElement
#
public partial class TextMeshProUGUI
scarlet viper
#
ren.material = null;
ren.sharedMaterial = cachedMaterial;

Anyone knows how to force renderer to stop using instanced material, and use its original material (sharedmaterial) instead ?

gray mural
#

oh, no, that's TextMeshPro

eager yacht
#

What does that have to do with anything

#

It's edited in three places in their api. I've given you all three.

dusk apex
#

Cache the line info struct and view it in the debugger - it should be a field in the text info class

#

It would be an array

gray mural
dusk apex
gray mural
eager yacht
#

Yeah

gray mural
#

Ok, so I have debugged it when I get error

if (_textComponent.textInfo.lineCount > _textComponentLineCount + 1)
    ;

text = "jfds;jfsdfldsfdsjkfdsa;dfsjfd;lskfdsjk;f;dsjk"
totalCharactersCount = 45

yeah, and lineCount = 45 too

#

and lineInfo.Length = 64

#

not the lost logic probably

#

also lineInfo's 0 - 44 lines have characterCount = 1, other have 0

#

well.

fresh cosmos
#

so im not entirely sure what to look for, im trying to create an exception that extends UnityException, but if i try it im apparently missing something as it doesnt log the error in the console. if i add the log manually with debug, as expected it open where the log came from not where the error was

leaden solstice
#

I don't think you ever need to extend UnityException

simple egret
#

Dumb question, but you're throwing it, right

fresh cosmos
#

yeah ofc

fresh cosmos
fresh cosmos
gray mural
#

does anyone know how can TMP_Text.textInfo.lineCount be 45, when there is just one line without any \n?

eager yacht
#

What's the full string? I can test on my end if you want

gray mural
eager yacht
#

Alright

gray mural
#

this is full string

gray mural
#

I just type and type and type... Like everything is absolutely ok when lineCount is one line more than _textComponentLineCount (default) - then I change _textComponent.

#

But like every 6th time lineCount is not 3, but.. 17, 36 or 45

#

that's very strange

eager yacht
#

Gives me 4

gray mural
eager pewter
#

This is less of a Unity issue, but I figured I would post the question here incase anyone had any ideas. If not, all good! I know this is a bit out of the server's wheelhouse.

Ok, I made a short video of me trying some things to provide a better idea of what's going on. I will also provide the code in text format so you can see it w/o having to look at the low-res video (my laptop is a potato, sorry about that).

Basic Unity example from video - TextCreator.cs: https://hastebin.com/share/zibariqema.csharp
BepInEx mod - Main.cs: https://hastebin.com/share/iwolezater.csharp
BepInEx mod - TextTerminal.cs https://hastebin.com/share/suwituzegi.csharp

I'm happy to provide any additional information & try various things. Thanks for any help you can provide!

eager yacht
#

Ah line count is based on the lines of the mesh. Which is why it gets calculated when the mesh is generated. @gray mural

gray mural
#

it skips one or more lines as you can see on this video

eager yacht
#

well what's the script

#

Was it the one from earlier

gray mural
#

yeah, just was testing it and added smth there

#

it's almost the same, yeah

eager yacht
#

Alright I will see what it does

gray mural
#

and yeah, I change textComponents to increase productivity

eager yacht
#

can you make a scene for this with the stuff assigned and export a package so I can import it and test with the exact set-up you have? (just scene, whatever prefab, then export a package and select the scene and the prefab it uses)

gray mural
harsh ridge
#

i seriously doubt that this is the best and most efficient way to do this so i ask if anyone knows a better way, basically i want to make a game where you make sentences and the game will turn those sentences real. for example the sentence "increase everyone walkspeed" would increase everyones walkspeed i already have this working but its not really modular and it seems like it would take a long time just to add new words. this is the script that i have made:

gray mural
#

is it possible to download Unity project from GitHub ?

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.

eager yacht
#

If it's on github and public/or you invite someone sure. Although exporting a package should be quite quick.

gray mural
leaden ice
harsh ridge
leaden solstice
harsh ridge
#

yeah kinda

leaden ice
#

This should just be a single loop over a list of, for example, ScriptableObjects

harsh ridge
harsh ridge
eager yacht
#

@gray mural I can't replicate the issue. It doesn't skip any lines for me.

gray mural
eager yacht
#

I followed that

#

Doesn't happen for me shrugs

gray mural
# eager yacht I followed that

probably that may not happen with first few textComponents, you can see if it happens within Texts GameObject, when more than one text is added simultaniously

eager yacht
#

oh I really had to hammer it with multiple keys at once and spam annoyingly fast

eager yacht
#

Yes

gray mural
#

you can also set break point here

simple egret
#

Breakpoints can be conditional! Hover over the red circle and hit the cog icon

eager yacht
#

why is there a coroutine in a coroutine and why are you not actually using the coroutines lol.

#

Don't know why you would even need coroutines here

gray mural
#

and it the same happened in Update

#

but there there were almost no normal changes

#

so I used to get that issue everytime

#

much more issues

#

so I have done coroutine

#

do control whether this coroutine is working.

eager yacht
#

They don't do anything though 🤔

gray mural
#

they help a bit, but this issue isn't gone

gray mural
#

everything should be ok when you "experimenting"

#

that's why I have been experimenting for 1 month already

eager pewter
gray mural
eager yacht
#

I'm still trying stuff out

frosty surge
#

Hi i have a problem i made a moving platform with two waypoints and have in the script distance which compare the distance between the platform and the waypoint if its less than .1 we increase the array index but the problem is that the if statement isnt working at all cause the "work?" message isnt even displaying in the console
PLS HELP ME

steady moat
# harsh ridge i seriously doubt that this is the best and most efficient way to do this so i a...

You want to use Polymorphism/Interface. In your case, you might modelized the concept of Token which represent a symbol or an ensemble of Symbol. The simplest way to create a "interpreter" is to parse the entry text in Token which can be interpreted.

However, I do not know the characteristics of what you are doing, thus it is kinda hard to suggest an architecture that fits your needs. The only thing I can suggest is to group up Action, Concept, People, Intensifier under the same label. Then you can add function such as WordType and CorrespondTo.

Dictonnary<WordType, int> counts = new Dictonnary<WordType, int>() { ... };

for (int i = 0; i < words.Length; i++)
  for (int j = 0; j < tokens.Length; j++)
    if(tokens[j].CorrespondTo(words[i])) 
      counts[tokens[j].WordType]++;
harsh ridge
steady moat
harsh ridge
#

alr thats fine

eager yacht
#

@gray mural I am out of time to try this out atm, but it's something to do with how you parse the text alongside when a wordwrap occurs. It emits twice which then splits the text even smaller than it was before, then makes a new text with that now smaller text (which skips a line). After you fix this, drop the nested coroutines for the text, as they don't do really do anything. When they run they just instantly quit, which defeats their point. Hopefully this was useful info for you.

ionic grove
#

Do you guys know how I can make an equivalent to GetKeyDown() that only fires once you press and not when you release with the new input system?

#

That's what I thought, but it also returns false when I'm not pressing the button

#

You know how you can use GetKeyDown in an if statement and it only fires once?

somber nacelle
#

the started event does only fire when the action is started though. you need to show relevant code and explain what is happening if you are experiencing some other behaviour

ionic grove
#

Hmmmm.. Maybe I'm doing it wrong. It was treating it more like GetKey(). I'll give it a shot and screenshot the code if it's not working

somber nacelle
#

please do not screenshot the code. if you plan to share the !code then do so using the bot's instructions below 👇

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
#

this is a code channel. see this message for troubleshooting steps for when the editor and stuff fails to install: #497872469911404564 message

ionic grove
#

Just a bunch of falses

somber nacelle
#

you know the difference between a bool and an event, yes?

pure dragon
#

How would I access a variable in a class that uses composition cleanly without needing inheritance?

somber nacelle
#

get a reference to the instance of the class and access the public variable using the . operator

pure dragon
#

ok but what if i had a class called Enemy.cs that uses composition (sorry), with each subclass of enemy defining their own attributes, how would I access it then? if two different enemy classes had the same attribute how would I access it?

somber nacelle
#

get a reference to the instance of the class and access it's public variables using the . operator

#

or do you mean you have a variable of that base class type and you want to access the inherited class's members? in that case you need to downcast to that inherited class

#

then you use the . operator to access its public variables

pure dragon
#

i dont think you are understanding, i cant just get a attribute with monster.walkspeed for example because what if i wanted to get the players walk speed as well, or set both, I would need to use a massive if statement for each type of class

gray mural
ionic grove
somber nacelle
somber nacelle
pure dragon
pure dragon
somber nacelle
#

well that's not what composition means. but again, none of what i said is incorrect

pure dragon
#

and I cant exactly go setting the parent class such as Enemy.movespeed as an enemy such as a turret would never use this variable

somber nacelle
#

why do you keep insisting you are not using inheritance then immediately describing inheritance as what you are doing?

pure dragon
#

the Enemy superclass is only used so that i can put all enemies in a list for example

somber nacelle
#

so i will reiterate, you need to get a reference to the instance of the object you want to interact with. you can use type checking/casting to downcast to your desired subclass and access its public members using the . operator

pure dragon
somber nacelle
#

again, use interfaces. but you cannot get around the fact that if you are storing the objects as the base class then you have to cast to either the desired interface or subclass to access the public members that are not declared on that base class

#

there's no way around that no matter how much you want to insist you want to do this "cleanly" or don't want to use if statements

pure dragon
#

hmm well thanks for the help but I dont know if that really answers my question. Although i must admit i am probably going too deep with the level of modularity in my code, maybe I can find a workaround using strings or something which also would suck but at least means I dont have to write a wall of if statements to change variables.

fresh cosmos
#

quick question. if i do

CancellationTokenSource source = new CancellationTokenSource();
source.Token.Register(() => cancel());
TaskFactory factory = new TaskFactory(source.Token);

does this mean that whatever task i start with the factory should get cancelled if the token source cancels it? and does all async methods called by those again also get cancelled?

swift falcon
#

Hello, I am making a 2d game similar to flappy bird.
I have some objects that move from the right side of the screen to the left.
The problem is that all the objects' movement doesn't feel smooth and I don't know how to fix this.
Can anyone help me?

#

Every game object has this script:

#
public class Movement : MonoBehaviour
{
    private float MovementSpeed;
    private Rigidbody2D rb;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate()
    {
        //MovementSpeed = GameController.MoveSpeed;


        rb.velocity = new Vector2(-GameController.MoveSpeed, rb.velocity.y);

        if (transform.position.x < -40)
        {
            Destroy(gameObject);
        }
    }
}
eager yacht
#

@gray mural dunno why I wrote this, I guess I got fixated. https://www.nombin.dev/ypjvpuneug Uses the new input system, which you should be using anyway and not imgui events, and it handles the lines just fine. Didn't fix the start-up caret not being aligned, and I didn't add in line height calculating to get an accurate line height, since I don't really care to. Look through it, poke it, play with it, etc to see what it does. Should be straightforward. The set-up is the same as your existing one in the hierarchy/inspector.

jaunty needle
#

Guys I have a singleton instance that when loaded into the scene searches for a component and stores it as a variable but for some reason FindObjectOfType doens't work across scenes

#

Someone hep pls

#
    {
        PhoneController phoneController = FindObjectOfType<PhoneController>();
        if(phoneController == null)
        {
            print("The thing doesn't exist man.");
        }


        //print(messageRbs[0].name);
        //print(messagePositions[0]);

        for (int i = 0; i < messageRbs.Length; i++)
        {
            messageRbs[i].transform.localPosition = messagePositions[i];
            print(messagePositions[i]);
        }
    }

This is the script

#

I'm trying to store the position of messages when I leave and enter a scene

lean sail
#

Like this is one of the most descriptive errors out there

jaunty needle
#

Ok man pls just try to be helpful

somber nacelle
jaunty needle
#

Which is why I tried to find phoneContrller

#

When I load into the scene

#

But it just returns null

crude cairn
#

Why can't I edit the Mesh Name string field?

somber nacelle
lean sail
somber nacelle
jaunty needle
#

Bro

somber nacelle
jaunty needle
#

Why is everyone here so goddamn condescending

#

Yall can't have some patience to people asking for help?

somber nacelle
#

i already fucking explained exactly why the issue is happening then you go and ask how it is happening

jaunty needle
#

Boy

crude cairn
# somber nacelle are you doing something to it in OnValidate?

No I'm not using that method, I just declared it like this: [SerializeField] string meshName = "Road";

But in a referencing editor script I'm doing this:

    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        RoadGenerator myScript = (RoadGenerator)target;
        // adding some buttons
    }
somber nacelle
#

please don't remove code from methods you share when sharing code. that makes it harder to debug when clearly important context is being removed

crude cairn
#
using UnityEngine;
using UnityEditor;
using UnityEngine.PlayerLoop;

[CustomEditor(typeof(RoadGenerator))]
public class RoadPartEditor : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        RoadGenerator myScript = (RoadGenerator)target;

        if (GUILayout.Button("Clear Road"))
        {
            myScript.ClearRoad();
        }
        if (GUILayout.Button("Build Road"))
        {
            myScript.SetUp();
            myScript.GenerateMesh();
        }
        if (GUILayout.Button("Save Mesh"))
        {
            MeshFilter meshFilter = myScript.GetComponent<MeshFilter>();
            if (meshFilter)
            {
                Mesh m = meshFilter.sharedMesh;
                string path = "Assets/Proj/SavedPrefab/" + m.name + ".asset";
                if (AssetDatabase.LoadAssetAtPath<Mesh>(path) != null)
                {
                    EditorUtility.CopySerialized(m, AssetDatabase.LoadAssetAtPath<Mesh>(path));
                    AssetDatabase.SaveAssets();
                }
                else
                {
                    AssetDatabase.CreateAsset(m, path);
                }
                AssetDatabase.Refresh();
            }
        }
    }

}

oh my bad, that's the full code

somber nacelle
#

now show the entire RoadGenerator class using a bin site 👇 !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.

crude cairn
somber nacelle
#

well i don't see anything modifying meshName so it's probably something to do with how the editor related code. #↕️┃editor-extensions

valid solar
#

Hate to interrupt but hopefully this can be resolved quickly, how do i modify a RectTransform at runtime, nothing seems to be working

crude cairn
#

okay thanks

valid solar
#

void Awake(){ BarFill = transform.GetChild(0).GetComponent<RectTransform>(); width = BarFill.rect.width; RectTransform thisRect = this.GetComponent<RectTransform>(); BarFill.rect.Set(thisRect.rect.x, thisRect.rect.y, thisRect.rect.width, thisRect.rect.height); }

#

dunno how to paste code properly mb

valid solar
#

i usually paste images

somber nacelle
#

okay now go ahead and describe what exactly isn't working

valid solar
#

its not applying anything to the referenced RectTransform at runtime, neither from manually assigning the reference or getting the reference at run time

somber nacelle
#

are you sure you are operating on the correct object? notice how your field is serialized which allows an assignment via the inspector however you are re-assigning it in Awake

valid solar
#

yes I tried by commenting it out

crude cairn
somber nacelle
crude cairn
vague hazel
#

How much c# do I need to know to use unity well

somber nacelle
# valid solar yes I tried by commenting it out

alos just FYI but i don't think calling BarFill.rect.Set is going to modify the rect, properties that are values types return a copy of the object so BarFill.rect returns a copy of the Rect object so the Set method would only be modifying the copy. that line in the Assign method with parameters would be how you can moify the rect

valid solar
#

well BarFill.SetSizeWithCurrentAnchors doesnt work either

somber nacelle
#

are you certain you are actually calling it?

valid solar
#

yes I have previously used it on the Assign function that is visible through the context menu

somber nacelle
#

have you ensured that the values you check in your if statements are what you expect them to be?

valid solar
#

the width is being assigned properly with a value of 192, and its being multiplied by a value lower than 1 through either Percentage or BarFillAmount, considering SetSizeWithCurrent Anchors takes Size, I'm assuming the value passed should be its actual Pixel length

somber nacelle
#

also i just realized, why are you doing all this when you could instead just use a filled image or even a slider (filled image is better) for a bar fill UI object

#

redirecting people to answer your question in another channel is crossposting which is against the rules

valid solar
#

yknow what, I totally forgot about filled Image. However, I didnt want to use sliders cause I didnt want all the functionality to clutter up my Inpsector

#

Regardless though, its still weird that it just straight up doesnt seem to work

rain minnow
# vague hazel How much c# do I need to know to use unity well

Unity is a game engine; learning the editor and how GameObjects work is good enough to use it. C# is just the programming language used to make games in Unity. Knowing it won't help with using Unity but allow you to make games with the engine

That being said, striving to understand the intermediate concepts of C# will prepare you for creating games . . .

vague hazel
#

alr so i dont need to be some god at c#

#

ik a bit

valid solar
#

yeah

#

you can do a lot of stuff with beginner knowledge of C# imo

#

it really just depends on what you want to make

simple egret
#

Learn up to classes and methods, I'd say, they're everywhere in Unity

valid solar
#

not to mention, a lot of stuff that makes your game feel/look good has nothing to do with code

rain minnow
valid solar
#

honestly just go on your own pace until you hit the feeling you're able to create stuff without pulling up a guide or tutorial

#

being able to read code that isnt yours as well is a great milestone to hit

#

or rather, understand it

simple egret
#

Yeah it just depends on the order you learn

#

Classes definitely wasn't one of the first things for me

#

Variables, types, arrays, loops, functions (top-level statements local functions) as a simple intro

valid solar
#

making while loops that dont crash

#

LMAO

rain minnow
#

Personally, you never stop learning. If you come across a new word, phrase, or pattern, look it up and/or bookmark it to read up on it . . .

valid solar
#

seconded

#

coding can be super fun, just making things and seeing it work is very satisfying imo

quartz folio
#

Psst, infinite loops freeze, they don't necessarily crash—there's a difference

quasi edge
#

I have a terrain object with trees on it and I want to be able to ignore the collision between my player and the trees occasionally

#

anyone know how to do this?

#

I know of the Physics.IgnoreCollision method but how do I do this for all the trees?

leaden ice
#

make a separate layer that collides with all the same stuff as the normal player layer, except for trees.

#

put the player on that layer when needed

quasi edge
#

hmm

#

isn't there an easier way to do this?

#

like somehow turn off the collider except only for the terrain

somber nacelle
leaden ice
#

it's like 2-4 clicks in the editor and a couple lines of code

quasi edge
#

alright ill try it

#

thank you

quasi edge
#

actually nvrm I think I found something that works

leaden ice
quasi edge
#

alright

quasi edge
#

I can set the layer and that seems to work

#

but somehow it can still interact with the trees

leaden ice
#

show how you set everything up

quasi edge
#

Ok so

#

the terrain has the "Invincibility don't ignore" layer

#

and the character has the "Invincibility On " layer for a 10 second period

#

heres what the layer collision matrix is

#

I can uncheck the invincibiliy don't ignore - and then the character falls through the terrain

#

which is what I would think happens

#

but then when its checked the character doesnt fall through the terrain but it can collide with the trees

#

oh wait

#

maybe because the trees are part of the terrain they also have the layer?

leaden ice
#

what about the trees

#

what layer are the trees on

#

the terrain should be on Default layer

quasi edge
#

actually i figured out the issue

#

its fixed now

quasi edge
leaden ice
#

why does the terrain need a special layer

quasi edge
#

I want the terrain to have its own layer to specify that its not ignored

leaden ice
#

why are you ignoring default

quasi edge
#

also I fixed the problem by checking this - so now the trees have a different layer than the terrain

quasi edge
leaden ice
#

why woould you want the terrain to be ignored

#

that means your player will fall through the terrain

quasi edge
#

the terrain isn't ignored

leaden ice
#

I would do it this way:
Player on layer Player
Terrain on layer Default
Enemies on layer Enemy

Layer setup:

default/default ON
enemy/default ON
Player / Enemy ON
PlayerInvincilble / Enemy OFF

When the player gets the powerup you move him to the PlayerInvincible layer, then back when it wears off

ashen yoke
#

to automate all of that

#

not in editor, at runtime, ie you have some WorldObject/Entity component that sets layer recursively in OnEnable

quasi edge
#

but I don't want to add the enemy layer to every different tree in the terrain

ashen yoke
#

you can also use Physics.IgnoreCollision

leaden ice
#

it takes about 1 second

#

first off - you only need to set the layer on the prefabs basically

#

just select all of them and set the layer once

#

that's all it takes

quasi edge
#

yeah i guess

#

alright ill do that

#

thanks for helping me

solemn raven
#

hey, Quick question.
is there is any advantage for int foo == 1? //do something : do something else over

int foo;
if(foo == 1)
{
 //do something 
}
else
{
 //do something else 
} 

performance wise especially with shaders??

ashen yoke
#

doubt it

dusk apex
leaden ice
#

the parts of the ternary need to be expression which return a value

solemn raven
orchid grove
#

ik this isnt the right place but im hoping someone could point me to it.
Im trying to find a dev to join w/ me on a project but i dont only want to hire them, i want them to be passionate about it too and enjoy the process. Any suggestions?

tawny elkBOT
orchid grove
cinder pollen
#

Is it possible to do a switch case on GraphicsSettings.currentRenderPipeline? Should I switch on the names, or what?...

cinder pollen
#

What are the cases?

leaden ice
#
switch (GraphicsSettings.currentPipeline) {
  case UniversalRenderPipelineAsset urpAsset:
    // code
    break;
  case WhateverTheHDRPOneIsCalled hdrpAsset:
    // code
    break;
}```
cinder pollen
leaden ice
# cinder pollen

you would of course need to include the appropriate using directive

#

as the error says

#

(as well as having URP installed/referenced)

cinder pollen
ashen yoke
#

i think this is the case where you should use defines

#

check defines in project settings and use them to if out the code

leaden ice
#

or if you have an asmdef you don't have it referenced

ashen yoke
#

what project would have both urp and hdrp?

leaden ice
#

My assumption is this is an asset store asset

cinder pollen
#

Maybe what I am doing isn't something you should be doing in the first place. What I am trying to do is host a tool on GitHub

ashen yoke
#

doesnt change much

cinder pollen
#

I want to set a material to use the correct Unlit shader

ashen yoke
#

you should write code targeting specific available assemblies

#

ie when odin installs it adds define "ODIN_V3" or something

leaden ice
ashen yoke
#

so you write code that both supports odin and doesnt```cs
#if ODIN_V3

#else

#endif

#

pretty sure SRPs have all the defines for that automatically added on install

leaden ice
#

I don't think they do

#

but maybe

#

It's also valid (but probably nonexistent in the wild) to have them both installed and to even change your scirptable render pipeline asset at runtime

ashen yoke
#

never considered that

leaden ice
#

use the first one you find

ashen yoke
#

i like this responce by unity

#

shows lack of understanding of the problem

leaden ice
#

but yeah ^ version defines in the assembly definition for your assembly

ashen yoke
#

"i want to write code so that if URP is not installed i would know"

#

"just use one of the classes in URP assembly to check"

leaden ice
#

which the version defines thing lets you handle

#

with preprocessor directives

cinder pollen
ashen yoke
cinder pollen
raven cove
#

Hello, I am using TMPro and I want to access the buttons pressed in an input field. TMPro has an input field script built in, but It looks like it doesn't derive from monobehavior. Is there a way to easily convert that script to monobehavior?