#archived-code-general
1 messages · Page 139 of 1
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
My project isn't big, just getting hung up on doing things "right", which is usually what kills my motivation.
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.
!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.
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.
does it make sense that handle rotates on the same axis like the door?
wdym?
I mean that handle should probably rotate by y axis
oh sorry i meant y
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);
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
does it even rotate?
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
your script looks very strange for me
Because Euler angles are awful
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 }
why do you even rotate from endRotation to startRotation ?
for Lerp
I want it to go from endRotation to my startRotation
in a certain amount of time
what do you suggest I go switch to? I thought Euler was the only thing for rotation
You cannot create Monobehaviour with New
You must create a GameObject and attach it with AddComponent
Quaternions
Your issue is you're expecting some specific Euler angle combination for your quaternions
I mean that's just one way to create a quaternion
This is your issue. Euler angles are not unique
would Quaternion(new vector 3()) work?
No
You're not understanding
Quaternion.euler isn't the issue
It's you reading the results as Euler angles that is the issue
@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);
You're worried about which Euler axis it's rotating on
Uhhh no
You are mixing up quaternion components with Euler angles
Very wrong
transform.rotation.y < very bad
what's wrong here?
oh, I have multiplied rotation
alright so what would I use to rotate a gameobject from one point to another
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
Still has the same error
Definitely won't be fine
what error?
yeah, so you can suggest your implementation
Praetor is talking about you accessing transform.rotation which returns a Quaternion
^ this error
Rotation x isn't the expected Euler angle value.
Neither is y and z
you rarely ever want to access a Quaternion’s .x
or any of its specific components
how else are you suppose to rotate objects though?
By not using the x, y and z components of quaternion.
but isnt transform.rotation already a Quaternion
if I want to change that I would have to use another Quaternion
Honestly. Confused why a code solution is being used instead of an animation solution.
They aren't Euler values
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);
let me try your solution
I see what you meant, that should work now 🤔
also this lerp uses a = Lerp(a, b, t)
I hate rotations.
yes, it does
meaning it will "speed up" in its rotation, unless its intended to have this exact effect
T should be a value that goes from 0 to 1
yes, ok ??
c = Lerp(a, b, t)
slow down*
ok?
rotation speed will approach zero the farther into the rotation it makes it
huh, how would it slow down
visually it would look as if its speeds up, a is getting closer to b while increasing t
Your lerp isn't proper
The t is constant in that solution
ho would you like to change it?
So it will slow down
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
what's that? it's formula I have used, yeah
Your formula was a = Lerp(a, b, constant t). Importance is a and t
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
Google how to properly use lerp with Unity
even the link u sent doesnt agree with what u wrote
I’m unsure of the context behind this, but you will first need to add the component to an existing ui game object. You can’t new components. https://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html
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
yeah, I'm looking into that now
Use the second example, not the first
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?
Oh, I see now.. Thank you!
that was a really nice explanation
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
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
It would be valid, assuming rotation speed is equal to time
no, I just forgot to change it by time
Quaternion.Lerp(startRotation, endRotation, time);
thx for reminding
thats what I already wrote
just with different variable names
still rotates on the z
Show what you wrote?
it cannot
actually that's your code...
endRotation = Quaternion.Euler(new Vector3(-90, 0, 0)); // Setting end rotation to -90 on the z
yeah, show your code
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
}
show full code
yes, you just do nothing here
no rotation happens at all
startRotation == endRotation == transform.rotation
you haven't
Quaternion startRotation = transform.rotation;
Quaternion endRotation = Quaternion.Euler(StartRotation);
Vector3 front_handleEulerAngles = front_handle.transform.rotation.eulerAngles;
front_handleEulerAngles.y += 40;
Quaternion front_handle_endRotation = Quaternion.Euler(front_handleEulerAngles);
that's full code you have sent
thats for my door script
I mean my door rotation
yeah, send full code
its literally in the code I sent
no, it's not
oh
I see
that's in DoRotationOpen
I was looking on DoRotationClose()
Yea, dont worry about doRotationClose()
thats why I didnt send my full code before
ngl the variable naming is only slightly confusing. startRotation and StartRotation
yea, sorry about that I kind of rushed to write the code
yeah, with those _ ..
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));
}
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
front_handle.transform.rotation = Quaternion.Lerp(front_handle.transform.rotation, front_handle_endRotation, time);
you should assing startRotation
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.
assign it before while loop as I have shown you here
and that's how your rotation should actually work
it still rotates on the z
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
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?
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);
do it in while loop @stark jacinth
print($"{front_handle.transform.rotation}; {front_handle_endRotation}; {time}");
i changed it and it didn't work
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
🪲 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
Very unlikely this is a unity bug.
no, I just wanted to see what this command does
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
what are you expecting instead?
to fall like in real life
so let it fall
normally a tree doesn't rotate
without giving force it stay in place
a rb doesn't need force to fall
add slight force from your characters forward
but not rotation
^
also GetComponent<Rigidbody>() is redundant
you already stored the component in rb when component is found in TryGet
okay thanks
you can up the angular drag to stop it from rotating so heavily
or deter it at least, since it still can rotate
hmm I'd do
AddRelativeForce or AddForceAtPosition on the axe hit would be better
i think the issue mainly is just the trees collider is like a cylinder though, at least thats what it looks like
ofc it's always a game, doo whatever looks /feels best
doesn't have to be totally real
yep, i changed it to box collider and it doesnt fall weirdly now
take mc for example lol
insta-boxes
only issue with a box collider might be you'll see the tree jump up slightly if the box does roll from a lot of force, but i assume its probably much rarer and better than having the cylinder which always has a bad effect
If the goal is to not have rotations at all then you could probably just lock the y rotation on the rigid body altogether.
^
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
it will fall on a side
and often times it looks goofy for a tree to rotate when falling
im talking about before it lands completely. Once it falls, it doesnt matter if its locked or not
ye exactly
it would look a little more natural then to give boundries to y rotation
TBH
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
any rotation doesn't look natural, maybe on impact if it gets to roll
trees dont rotate generally when cut down
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?
no
well in this case is rotation around itself
i think
this will spawn the object as a regular game object, the object does not get deleted, you just lose the reference at the end of the scope
also itll be given a transform by default
!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.
When I type too fast - multiple textComponents are changed. How to avoid it?
https://gdl.space/uqurocexiv.cs
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
is there any function that allows me to run a function for a fixed duration of time?
meaning run the function every frame for a few seconds?
yes, wfs
could use a coroutine
WatForSeconds()
or a simple float based timer, a bool, and the Update
yeah i know thats one way
look into coroutines
doesnt it run the function after some time has passed?
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
it is
you use coroutine and break it after some period of time
up to you how you want to make the timer
float, or coroutine
or yeah what they said
well i will call the function X after bool isY gets to true but the function X should run for say like 1f seconds..
just look into coroutines, it'll do what you want
yessir
(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
"if Y is true or if time has passed already"
you don't instantiate o
not the best name actually
? do I not make a new GameObject for it?
yes, you have to Instantiate it
no u dont
it won't appear in scene otherwise
GameObject obj = new();
obj.name = "_PlayersManager";
_instance = obj.AddComponent<PlayersManager>();
oh
does it happen thanks to this line?
_instance = obj.AddComponent<PlayersManager>();
no, u can just do new GameObject() and it will spawn with a transform
that's strange
I thought that doesn't work so
new() is just short hand for new GameObject() btw
i just use this for a singleton, thats why that line exists
yes, I know this
Well I finally got this stupid marching cubes thing to work... So I'm going to bed. Cya o/
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
guys i need help
my project keep crashing
it show "failed to build mask for shadow culler" error and then crash
help
do you sucessfully instantiate GameObject with TextMeshProUGUI ?
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?
look for it in the scene hierarchy, also if you have it as a transform and not recttansform then the text will look very small
can anyone help me with my situation in #💻┃code-beginner message
dont crosspost it in here. also post your code properly in there instead
Unfortunately I can't check the scene hierarchy due to not having access to the editor (see my first post linked above)
that said...
I can confirm that the objects exist
and that they do have a TextMeshProUGUI component
are you setting its parent to be a canvas
sonds like you need to learn how to do screenshot
What you see here is (parent's parent | parent | object | text content (empty))
nah, this computer laggy af when the game's open. Takes like 30 seconds for it to even begin to register that I've hit the screenshot key
nice.
besides, I've been using screenshots this whole time. Just didn't feel like waiting a minute for this one simple pic
use Snipping Tool
honestly even with u saying this, i dont know what i am looking at
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
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
can you show the entire code with a code site?
sure
or whatever is completely relevant, because from before your OnGUI was questionable
just the relevant stuff -> https://hastebin.com/share/ujupuhocip.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
yea yourfriend pointed out before but its OnGUI() not onGUI(). But this will also heavily spam you from my experience
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
you arent changing 1million of anything every frame without lag
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
ah i understand
Well then what are my options
Maybe pass an array of all the colors to a shader?
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
you wouldnt pass an array, though i have no clue what these values are based on or what you are trying to do so its hard to really suggest. I doubt you really need all 1m updating every frame
I may have an update... (posting this pic for my own reference)
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
is it working? 🤔
the only thing i could think of was it might be a transform not recttransform but i have no clue otherwise
yea but u likely arent looking at all 1m things at once right
shaders can take a float
Well not 1 float
2d array of floats
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
is this 2d array also 1000 * 1000 by chance?
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
you probably need some ecs/jobs/burst thing or have this run with some compute shader
could be valuable looking at those youtube videos about rendering massive amounts of objects. I dont know too much else about this
Yup thanks
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
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?
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
can I leverage unity's navmesh pathfinder on a grid system or do I just need to make my own (A* algo)
What do you mean? Auto complete?
What do you mean by that? Text component index would be the field
You mean value?
Definition?
I mean this
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?
If you're debugging with your ide, you should be shown a details pane with all values of variables in vs.
where should I be shown?
yes, I cannot see it in some values
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?
Well, the difference between the two images you've shown above is that last line is a field and text is a property
oh, you have sent a link too.
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;
}
Uh... Where should I ask help on an crashing issue with this? https://docs.unity3d.com/ScriptReference/NVIDIA.GraphicsDevice.html
!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.
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
gpt ... is it right?
#📖┃code-of-conduct
- • Ask or answer questions using unverified AI-generated responses.
! sorry
this windows appears every time I do it, regardless what value I am hovering
I guess it's another window
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];
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.
I probably do it correctly
Hey! Hi! Could someone help me display a dialogue system?
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.
I followed a tutorial series, and everything turned out wonderfully, except for the part of displaying the dialogues in-game, because it didn't touch on that.
I've already made a displaying thinghy for a different SO-based Dialogue System, but I can't seem to get this one going.
Probably show what* you've tried so far to give an idea what it's supposed to do
So, if anyone could be kind enough to guide me in the right direction, I'd be really thankful, (Also I can send you the node-based dialogue system, for future usage xd)
Thanks Ill try it
Let me open unity back up
Ok, so, I have this entire Node-Based dialogue system:
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?
lol, I followed that tutorial a few weeks back,
Never made a way to display it though...
Did you end up displaying it in-game? I can't wrap my head around it
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
If I end up figuring this out before that, I'll be sure to let you know, if not, I'd love you if you did the same xd
Thanks, and for sure
could make the parts rigidbodies and enable/add/toggle kinematic when the player dies.
and detach the gameobjects if needed
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
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?
the log file path is not located inside the built game
it's some other (platform dependent) path
the logfilepath is just for debugging, because i wanted to check the filepath was correct and such
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
perhaps loadedObject will have some information about the problem
i don't know what the type is
it actually didn't
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.
Sometimes visual studio has a hard time analyzing values and fail. What I do intead is use the Action function to print the value
so I can now do it just like this:
var foo = _textComponent;
how would you do that?
On the break point
There is other option
You use the action one and do {_textComponent.name}
you mean this?
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
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.
well this is loading scenes which has a built in progress
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)
I do not know. You can probably test it by lokking at the current frame from Time.frameCount. However, it does not seem to make any sense to use Task.Delay in this context.
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)
The direction is correct
You can use Debug.DrawLine or Debug.DrawRay to visualize the ray.
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
thanks
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();
No encryption is the fastest
Ask yourself if you truly need it.
i use encryption just to discourage for cheating
Cheating for what type of game in what circonstance.
a game a bit like geometry dash
So, a solo game ?
but you can share levels
Then, you cannot prevent cheating.
but i wan t to discourage for cheating
Which means, that it does not matter.
i wan t to make cheating not extremelt easy
beceause you will be able to have more obstacles to add in the levels
that you can share
I do not understand.
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.
Cheating, only matters in Online game.
And even there.
Some type of Online game can be fine with cheats.
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?
No, I do not. Would it matter if people have infinity level ?
Except, screwing up your progression system.
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.
i just wan t to make that cheating is not easy
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.
It will not matter. Do not lose time for something that does not matter.
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.
The fact that your game is on Android is already a major deterrent for almost anybody.
that mean it s so hard to cheat
However, any layer you gonna add on the client side will have no effect what so ever.
where are the files stored?
ok i think i know what to do, i put a random file extension and that s it
without encryption
split the data into multiple file and increase the io time
i have multiples files yes
ok thks for that i won t encrypt the datas
It'll require more effort on their part and yours
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
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
it will eventually complete yes. It returns an AsyncOperation IIRC which you use to check when it's complete
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
can you link the documentation or this function?
I don't actually remember where it's from
have you tried sometjing similar to the example in the docs?
What does your code look like
I initially tried just putting all the requests into a list and doing a busy wait for completion in a coroutine
you can just yield return the handle it gives you back (as per the example)
Can you show your code?
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
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
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
What's your ultimate goal? Why do you want the euler angle rotation? Usually your problem can be solved or easily by not using Euler angles
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
I have mentioned that everything executed even when line above has not executed yet. How do I avoid it?
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:
upon hitting play it reverts to the default state
Most likely your code is setting it in Start or Awake
For comparison, a node that works correctly has the "prev point" variable properly bolded out like it should be:
Did you correctly save the state in the Prefab ?
WDYM? In the prefab it's "null" like it should be?
Nope, my "awake" is literally just one line of _gm = GameManagerGlobal.Instance;
you'd have to show the code
that's just one function
Maybe show your code if it's code related
I'm unsufe if it'll fit in Discord, but sure, a sec
!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.
@thin hollow ^
Call this method after making modifications to an instance of a Prefab to record those changes in the instance. If this method is not called, changes made to the instance are lost. Note that if you are not using SerializedProperty/SerializedObject, changes to the object are not recorded in the undo system whether or not this method is called.
// 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.
Here's the code that sets up the connections:
https://hastebin.com/share/tinezorigo.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
You are doing the process in a DrawGizmos ?
Do not do that...
Use OnValidate at worst.
OnValidate is called only once, no?
Each time you make a modification on the inspector of the object.
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
Anyway, OnDrawGizmos is definitly not the best way to achieve what you want.
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}");
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.
And I see no mention of RecordPrefabInstancePropertyModifications
How what's possible?
That's because I learned about that just a couple minutes ago. 😄
how can lineCount be 17 if text is dkjfkdjsfjkdskfds ?
It doesn't make sense for me
Did you look into what lineCount is actually is.
and that's issue I get every 5th time
not really
and when it gets refresh
Then do it. TMP is open source.
I change _textComponent when lineCount > _textComponentLineCount (2 in our case). It's 3 in this case, but sometimes 17 or more
Maybe you've concatenated a bunch of new line characters 🤷♂️
there is no documentation for this
Also, check the docs
Look into the code...
no, I cannot
https://docs.unity3d.com/Packages/com.unity.textmeshpro@1.1/api/TMPro.TMP_TextInfo.html and you can view the implementation with your ide
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)
yes, that doesn't contain explanation for lineCount
Look directly in the function that updates lineCount from the code.
And the second part of my remark?
what do you mean by "view the implementation with your ide" ?
Go To Implementation, yeah
it goes to TMP_TextInfo class
nothing in TMP_TextInfo
it's updated just to 0 when cleared
Who owns lineCount ?
what do you mean?
Where the field resides ?
it's TMP_Text.textInfo.lineCount
Alright, could it be possible that the field is exposed ?
in TMP_TextInfo class
of course
public int lineCount;
Then, find who modify the values.
It worked like a charm, thank you! Kind of ridiculous that you need to run such an important function manually, but oh well...
As per the documentation, you should modify object through SerializedProperty
In other words, you are not doing it the intended way.
But I marked the variable as serialized
it edited in neitherTMP_Text nor TextMeshProUGUI
It is not the same thing.
It is almost impossible that is not.
it's not edited there
Ah, so whenever I have a code that changes itself or other object in the editor, I need to run this function, right?
I cannot find it with Ctrl + F
Bro
just lineInfo is edited
Code that are part of a prefab, yes.
In the first two functions I gave you. In the clear it sets it to zero.
You're probably navigating through decompiled code, reference and usage metrics might be inaccurate
Hm, it won't cause any issues if it ends up in a script that isn't on a prefab?
by accident
Who knows. You can check with IsPartOfPrefab
oh, yeah, I haven't mentioned that's TextMeshPro class
that's the only place
I have no idea what that is supposed to tell me. Every time the text's mesh generates, it calculates the line count
how can i throw an exception that can highlight an Object as context in the project files like how debug.log() can?
Can you show the complete code?
It doesn't calcute it. lineInfo's length is edited in InsertNewLine() method
i assume i have to make my own exception for that maybe? unless there is arealdy something that i don't know about
You can use public static void Log(object message, Object context); ?
how to delete current .material and make the renderer use its .sharedmaterial instead?
where is it?
i want it to be an exception though
Again, in the first two functions I gave you.
There is EditorGUIUtility.PingObject();
i'm think once you access the material property you lose the reference to the sharedmaterial entirely, so you'd have to store a separate reference somewhere before doing that
can you say which one?
Both of them
no, actually it's just another part of TextMeshProUGUI
it's partial class
public partial class TextMeshProUGUI : TMP_Text, ILayoutElement
public partial class TextMeshProUGUI
ren.material = null;
ren.sharedMaterial = cachedMaterial;
Anyone knows how to force renderer to stop using instanced material, and use its original material (sharedmaterial) instead ?
oh, no, that's TextMeshPro
What does that have to do with anything
It's edited in three places in their api. I've given you all three.
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
I cannot view it. I have said about this issue some time ago here.
I recall you couldn't view properties (which are methods). I'm not on a workstation right now but you should be able to view your local copy of a struct.
local copy? you mean:
var bla = _textComponent.textInfo.lineInfo;
Yeah
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.
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
You could just try logging exception with Debug.LogException ?
I don't think you ever need to extend UnityException
Dumb question, but you're throwing it, right
yeah ofc
well i dont need to i just thought it could be interesting to learn more about exceptions
that logs properly though it still open the line where the log is but maybe it properly opens when the package is installed in a project
does anyone know how can TMP_Text.textInfo.lineCount be 45, when there is just one line without any \n?
What's the full string? I can test on my end if you want
jfds;jfsdfldsfdsjkfdsa;dfsjfd;lskfdsjk;f;dsjk
Alright
this is full string
that's still the same issue.
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
Gives me 4
yeah, it won't probably work for you without my script
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!
Ah line count is based on the lines of the mesh. Which is why it gets calculated when the mesh is generated. @gray mural
yeah, that's how it should work
@eager yacht
it skips one or more lines as you can see on this video
yeah, just was testing it and added smth there
it's almost the same, yeah
Alright I will see what it does
it's custom Typing Field that catches Input with Event in OnGUI and changes _textComponent.text with text Property
and yeah, I change textComponents to increase productivity
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)
yeah, hold on
but can you get it from GitHub or not?
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:
is it possible to download Unity project from GitHub ?
!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.
If it's on github and public/or you invite someone sure. Although exporting a package should be quite quick.
@eager yacht
Making it work with natural language would basically require a large language model / ai
yeah, I have done it
im not looking to make it work with natural language, my issue is that for every word i have to code a new section like if the word walkspeed is used the game has to check a few variables and its fairly managable but i feel that when i start using way more words and word types the script is going to be hard to manage
So something like Scribblenauts?
yeah kinda
Make it data driven not code driven
This should just be a single loop over a list of, for example, ScriptableObjects
i have no idea what you mean
do you have an example?
@gray mural I can't replicate the issue. It doesn't skip any lines for me.
look on this video, the issue happens when you are probably typing very quick
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
oh I really had to hammer it with multiple keys at once and spam annoyingly fast
did you get this issue?
Yes
you can also set break point here
Breakpoints can be conditional! Hover over the red circle and hit the cog icon
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
yeah, thanks, I see now
because I first tried doing it in Update
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.
They don't do anything though 🤔
they do smth.
they help a bit, but this issue isn't gone
also I have implemented coroutine, because I didn't know the real reason of this issue and how to fix it
everything should be ok when you "experimenting"
that's why I have been experimenting for 1 month already
Imma bring this down in case anyone's free
I have updated the code as follows:
if (_textComponent.textInfo.lineCount == _textComponentLineCount + 1)
{
// ...
}
But it still skips one line, I am now actually very not sure how it works.
I'm still trying stuff out
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
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]++;
is it ok if we talk in dms for a minute?
No.
alr thats fine
@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.
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?
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
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
please do not screenshot the code. if you plan to share the !code then do so using the bot's instructions below 👇
📃 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.
this is a code channel. see this message for troubleshooting steps for when the editor and stuff fails to install: #497872469911404564 message
public void OnInteractPressed(InputAction.CallbackContext context)
{
interactingPressed = context.started;
print(interactingPressed);
}
Just a bunch of falses
you know the difference between a bool and an event, yes?
How would I access a variable in a class that uses composition cleanly without needing inheritance?
get a reference to the instance of the class and access the public variable using the . operator
for example, here are some ways you can reference a unityengine.object: https://www.youtube.com/watch?v=Ba7ybBDhrY4
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?
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
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
I am sorry, I don't understand what do I need to fix.
I think you were talking about this parsing:
string lastLine = text[firstCharacterIndex..];
_textComponent.text = text[..firstCharacterIndex];
But I don't understand how do I split the text even smaller than it was before.
Ah yes I do, but haven't used them very often
- interfaces
- it sounds like your inheritance is all kinds of fucked up
okay well you were instructed to use the InputAction.started event. not to check the CallbackContext.started bool
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_started
that is because i am not using inheritence, I am using composition. composition means only the subclasses have info about each other for example
as in the variables are defined in the subclass i mean
well that's not what composition means. but again, none of what i said is incorrect
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
why do you keep insisting you are not using inheritance then immediately describing inheritance as what you are doing?
well technically yes there is one layer of inheritence here with an Interface called Enemy but apart from that the enemies themselves use composition for everything else
the Enemy superclass is only used so that i can put all enemies in a list for example
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
thats my point though, using type checking would suck as I would need to do a switch statement or something to type check every type of enemy to see if it has a variable
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
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.
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?
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);
}
}
}
@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.
A website to host temporary code snippets.
Any ideas?
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
The error tells u exactly what to do
Like this is one of the most descriptive errors out there
Ok man pls just try to be helpful
assuming the messageRbs array is the issue here, when and where do you assign it? because if you do not get the rigidbodies every single time you enter the scene then that is your issue. because each time you enter the scene those rigidbodies are different instances
I got that, I get them in start:
{
phoneController = FindObjectOfType<PhoneController>();
messageRbs = phoneController.rbMessages;
}
Which is why I tried to find phoneContrller
When I load into the scene
But it just returns null
Why can't I edit the Mesh Name string field?
Here
the issue is the messageRbs array, not the PhoneController object
Do you have interpolate on? You may want to use that or some custom interpolation
How so?
reading must be hard
#archived-code-general message
Bro
are you doing something to it in OnValidate?
Why is everyone here so goddamn condescending
Yall can't have some patience to people asking for help?
i already fucking explained exactly why the issue is happening then you go and ask how it is happening
Boy
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
}
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
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
now show the entire RoadGenerator class using a bin site 👇 !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.
RoadGenerator.cs:
https://hatebin.com/rqoyqeqyqc
well i don't see anything modifying meshName so it's probably something to do with how the editor related code. #↕️┃editor-extensions
Hate to interrupt but hopefully this can be resolved quickly, how do i modify a RectTransform at runtime, nothing seems to be working
okay thanks
show what you've tried
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
okay now go ahead and describe what exactly isn't working
its not applying anything to the referenced RectTransform at runtime, neither from manually assigning the reference or getting the reference at run time
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
yes I tried by commenting it out
I think this is a unity bug, I can't even rename any folders
have you tried restarting the editor?
yeah that worked
How much c# do I need to know to use unity well
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
well BarFill.SetSizeWithCurrentAnchors doesnt work either
are you certain you are actually calling it?
yes I have previously used it on the Assign function that is visible through the context menu
have you ensured that the values you check in your if statements are what you expect them to be?
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
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
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
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 . . .
yeah
you can do a lot of stuff with beginner knowledge of C# imo
it really just depends on what you want to make
Learn up to classes and methods, I'd say, they're everywhere in Unity
not to mention, a lot of stuff that makes your game feel/look good has nothing to do with code
Just up to that? I'd go further than that. Those are part of the first things you learn . . .
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
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
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 . . .
seconded
coding can be super fun, just making things and seeing it work is very satisfying imo
Psst, infinite loops freeze, they don't necessarily crash—there's a difference
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?
use layer based collisions
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
hmm
isn't there an easier way to do this?
like somehow turn off the collider except only for the terrain
that's basically what the layer based collision is
https://docs.unity3d.com/Manual/LayerBasedCollision.html
what is not easy about it?
it's like 2-4 clicks in the editor and a couple lines of code
how do I change it in code?
actually nvrm I think I found something that works
myObject.layer = theNewLayer;
alright
my code is not working and I'm not sure why
I can set the layer and that seems to work
but somehow it can still interact with the trees
show how you set everything up
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?
why the terrain?
what about the trees
what layer are the trees on
the terrain should be on Default layer
wait why?
why does the terrain need a special layer
I want the terrain to have its own layer to specify that its not ignored
why are you ignoring default
also I fixed the problem by checking this - so now the trees have a different layer than the terrain
because I want everything on the terrain to be ignored by default - so I don't have to add a layer to every prefab
why woould you want the terrain to be ignored
that means your player will fall through the terrain
the terrain isn't ignored
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
you can set layers in code
to automate all of that
not in editor, at runtime, ie you have some WorldObject/Entity component that sets layer recursively in OnEnable
yeah I think thats smart
but I don't want to add the enemy layer to every different tree in the terrain
you can also use Physics.IgnoreCollision
why not
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
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??
doubt it
No. They're similar in that there's a term being evaluated but differ in that the ternary requires an assignment and cannot process multiple statements without being less legible or tedious.
Thank you ❤️
The advantage is it's more concise.
Also note that "Do something" isn't really something you can do in a ternary, unless doing something is a side effect of returning a value
the parts of the ternary need to be expression which return a value
Great! , yup I agree! , thank you for explaining that ❤️
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?
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
ty, sorry i didnt see that
Is it possible to do a switch case on GraphicsSettings.currentRenderPipeline? Should I switch on the names, or what?...
switch on the type
What are the cases?
switch (GraphicsSettings.currentPipeline) {
case UniversalRenderPipelineAsset urpAsset:
// code
break;
case WhateverTheHDRPOneIsCalled hdrpAsset:
// code
break;
}```
you would of course need to include the appropriate using directive
as the error says
(as well as having URP installed/referenced)
It doesn't give me a using directive.
i think this is the case where you should use defines
check defines in project settings and use them to if out the code
Then you don't have URP installed
or if you have an asmdef you don't have it referenced
what project would have both urp and hdrp?
My assumption is this is an asset store asset
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
doesnt change much
I want to set a material to use the correct Unlit shader
you should write code targeting specific available assemblies
ie when odin installs it adds define "ODIN_V3" or something
you will need:
- an assembly definition
- that assembly definition to have assembly references to HDRP and URP
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
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
never considered that
how about just checking if the HDRP shader exists, then checking if the URP one exists
use the first one you find
i like this responce by unity
shows lack of understanding of the problem
but yeah ^ version defines in the assembly definition for your assembly
"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"
https://docs.unity3d.com/Manual/ScriptCompilationAssemblyDefinitionFiles.html#define-symbols
the package both needs to be installed AND you need to have a URP asset set as the currentRenderPipeline asset
which the version defines thing lets you handle
with preprocessor directives
Do you happen to know the name of the HDRP Unlit Shader off the top of your head? Is it "High Definition Render Pipeline/Unlit"?
The URP one is "Universal Render Pipeline/Unlit"
no
i would setup 2 projects with urp/hdrp to look up things while developing in third
I'm just mad it isn't in the docs somewhere lol, maybe I am missing it, but anyways, thanks for the help Scratch that, it is listed here https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@16.0/manual/Material-API.html.
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?
