#archived-code-general
1 messages · Page 117 of 1
Are you at constant 10 FPS ?
If so, you should see on the Profiler your "graph" being displayed at around 10 FPS.
You can click on any "spike" of the graph, and you should get the list of what is getting called and what is causing issues.
its not a constant , its like 10-13
thats still basically constant
Also, if you have a doubt with your code, you can add
https://docs.unity3d.com/ScriptReference/Profiling.Profiler.BeginSample.html
https://docs.unity3d.com/ScriptReference/Profiling.Profiler.EndSample.html
Which allow you to profile a specific set of your code.
do they have to be in the resource folder ?
oh I can profile check my own code
nice thanks
That the thing, I don't want to put them into the resources folder, or using asset database.
So I was wondering if I can get a List of sprites, from a Texture, with a specific method.
So far, I never find anything.
You're welcome.
As you can see on the right side, the blue part is taking a LOT of your FPS, and it says that blue is Script.
So now, on the bottom part (Main thread) you should be able to click on the part that are taking most time.
I would also advise you to swap from Timeline to Hierarchy (Just above main thread, click and change the layout).
How to handle tilemap walls?
Just curios if this would be a good approach for what I want to build, im making all my abilities as ScriptableObjects, that I plan to store in typed lists (like List<CarSO>, List<BikeSO>, etc), on a singleton then use that singleton to essentially act as a "shop" for different types of SO's, and allow the player to maintain a small inventory of various SO types, could this have a noticeable memory impact? Are there maybe other ways I could explore as well or should this approach be fine in this case?
thats likely your mlagent taking a lot of resources yes
you likely dont want to train an agent every single time you play
training is very slow from nothing
If you read the code, you can see that your root.DecideAction is taking almost 56 MS.
Which is ... HUGE.
ive had worse from the editor itself 🤷♂️
its bad still, but i assume this is only lagging when they are training
Is it possible to add a transition in animation controller that can checks if one of the provided values is true? (Like an or statement)
When do you prefer to define an enum with All, None and other flags (unions) instead of defining an array of a class type
In my view, when values of that enum type do not change (add/remove)
For example days of a week is known.
My exact scenario is
Each building/farm can be damaged/destroyed by different animal types
Mamals, insects, birds.
I can define an array of animal type as target
public enum AnimalType{}
public class Animal{
//...
public AnimalType Type;
}
public Animal[] Targets;
public bool DamagedByAll;
or
converting that animal type enum to flag enum
What does Take actions between decisions mean?
if decision period is set to 20 does it mean that for the next 19 steps its going to redo the same decision?
huh didn't you write this?
best way to seperate wall and floor collisions with a tilemap?
write what?
the script you asked a question about?
yes?
I wasnt sure if that toggle meant doing a random action between decisions for learning purposes OR doing the same action for the next n amount of steps
ALSO about my low fps, I dont see cpu or gpu maxing out and its struggling with fps
How are we supposed to know what something does in a script you wrote?
I didnt make that toggle there tho
its from mlagents
I should prolly have said that?
you should probably read the instructions...
your CPU won't hit 100%
unless you're effectively using all of your cores
you'll probably be bottlenecked by single-threaded performance
I should see 1cpu hit 100 no?
Not if hyperthreading is enabled
so what is bottlenecking then
I don't know anything about unity's ML agents, but it's a pretty consuming task in general
RTX GPUs have cores specifically designed for these calculations
like someone else said, you shouldn't be training while the game is running
so if I run in headless mode, ima see a bottleneck?
headless mode has nothing to do with this conversation
nor is it going to change how the learning calculations get processed
Headless mode gets rid of the rendering part. Rendering != machine learning simulation
I know
but Im also not really getting a straight answer why Im not bottlenecking
im tryna pull some answers
I don't think you understand what bottleneck means
something that runs at max capacity so other stuff has to wait for that thing
If you have hyperthreading enabled, your cores will not be at 100%
what
i think you need to get a handle on what your code is doing
Your GPU will only be used in the ML calculations if unity specifically designed it to
wwhere is the bottleneck
rather than trying to randomly guess what's happening
you guys lmao
If unity hasn't designed ML-agents to use tensor cores, it will not use your GPU
your GPU will be out of the picture
it does not matter
tell me how to find out what is bottlenecking then
lmao
please do not "you guys" me
simulation code DOES NOT RUN ON THE GPU
I already told you about 3 times
because its hyperthreading okay
if you have hyperthreading enabled, YOUR CORES WILL NOT BE MAXED OUT
BUT ONE CORE HAS TO RUN AT MAX??? NO?
how am I using less than 100watts total
The main issue is that you're trying to train during gameplay
The training should take place in a separate simulation
and it doesn't matter if it runs at 10 fps
You feed it an input and get an output. That's how machine learning works
so you're saying my code is limiting my fps?
You need to figure out how to offload to the GPU, so that it uses the tensor cores. If that's even possible with unity's implementation I have no idea
Judging from google searches, it's possible, but has worse performance than the CPU
you just need to not train your models everytime u play as i said 2 hours ago. Yes, this is your code, i dont know what answer you are looking for.
There will be some way to store the results, and then all you have to do is let it train once or however many times you want. Look into how ML works, or maybe just an overview of what it is and you will see why it is terrible to use everytime you play. If you dont understand the basics of it, you wont be able to tune it, and you'll wonder why your AI breaks.
There's also the question of "do I really need a full ML setup in my game?"
depending on the algorithm used, and the data size, training can take hours. For a game, training an AI to even aim properly takes a long long time
as well with what Burt said, a lot of "AI" enemies arent even AI. Just state machines, if statements, and randomness
Pathfinding as it is, is already extremely expensive on the CPU
throwing ML at that is just going to shit on your performance even more
You mean ML isn't the magic solution to literally all programming problems where you just throw data into a black box and solutions come out? /s
Part of the problem is unity advertising this stuff as a super duper easy drag and drop setup
This is going to be extremely complicated if you're involving physics.
If you can't figure out the basics of ML, you're going to have an awful time.
prolly
If the spider is going to try and walk by itself with joints, and you dont have any background in ML, you really wont get anywhere
these are the types of videos u see online that take days of training.
yup
Hacksmith did this IRL. An entire team of engineers did not succeed with this.
I made a function that would basically make it walk... really nice in a straight path but then turning becomes an issue. Could I "show" an ML my thing and speed up the learning process?
you mean the crawler thing with buckets for legs? that broke 10x?
ML requires a background in mathematics and statistics.
that isnt how ML works
Built by a team of experienced engineers with backgrounds in mathematics and applied physics, yes
I WAS hoping for this ngl
Look into actual ML like what a reward system is if you intend to continue with this
you would need something to tell you spider if it did good or bad, then it will adjust to try and maximize its reward function
You could look into control theory and PID controllers.
again, what you're trying to do is very advanced
I could do that, just not now cos of my exams coming up, after yes, now no. but I want to because Im starting studies in AI next year
and yes I think my reward system is shit for 24 inputs
you need to fine tune your reward system so some inputs are more rewarding than others. No ones really gonna be able to tell you what reward system to use, but if your spider works on joints then a high reward should be walking while not going past its joint limit
again though im even skeptical to say that as a high reward. The results are going to be shown after training
24 angles of how the legs could be turned and im rewarding if its getting closer to the target xd
yea thats not gonna work
i dont even know what that is for
I kinda knew it tho but like shit its actually bad
You need to interface with it using the physics engine.
Something like addtorque for rotating it
which is going to be difficult because of the legs being separate from the main physics body
Im limiting myself to the ideal world, it has only mass and gravity and 0 friction what so ever
Your rewards have to make sense as well for the goal, 24 angles -> spider walking doesnt make sense.
You want it to walk towards a goal, so maybe measure how long it took to get there.
if you base it off addForce in some way, one issue becomes that your AI will learn to launch itself to get to the goal in 1 frame and obviously u dont want that
addForce was just an example though, if you intend for it to walk only from rotations then u wouldnt use it
oh so my code wouldnt do that
all it does is add between -1 and 1 to the rotation clamped between its min and max rotation
oh but even if its a whole degree of movement I guess it could launch itself
unless I make the mass to be 999 tons 🤔
if theres rigidbodies and joints, it may still find a way but 🤷♂️ thatll be apparent after training
You have convinced me
aight its done, I closed everything I gave up
ill be back in a month to learn ml from start 
is there a way to change the scroll position of a scrollrect while dragging?
i'm trying to do a looping scroll, and i've done the math to loop the position back when i hit a certain boundary
but when i drag past the trigger, the scrollbar freaks out
Hi. A bit of an abstract question.
I always find it hard to organise data when it should be sorted by different values, for example: students, who answering some questions. I need to sort it by students, to know who and how answered on every question, and I also need to sort by questions, so I can get data of how many time specific answer were chosen and how many student answered the correct question per class.
So the difficulty I'm facing, is how to build the structure. I can create class Student who have property "List<AnsweredQuestions>" or I can create class Question, who have property "List<AnsweredStudents>". And either way, when I have to get Information from another structure (for example, when I decided to go with Student class and have to get statistic about all answered questions), I have to make a helper method, that go through all the students list, record all answers information and return it:
void GetQuestionAnsweredCount(Question question, string answer)
{
int answerCount = 0;
foreach (Student student in Students)
{
if (student.AnsweredQuestions.Find(question).Answer == answer)
++answerCount;
}
return answerCount;
}
The sample above is simple, but the complexity growth very quickly.
Am I missing a simpler solution? I feel like there could be a pattern to solve this, I hope I described the problem clear enough.
Object orientated programming doesn't grapple well with questions like these, where do you put data when it's not really part of this abstract representation?
Personally, I would avoid connecting these two unconnected things inside their own data structure. It doesn't make sense that questions know about students, or students know about questions beyond their ability to answer them or not.
So create another data structure from that information that is set up in a way that lets you use it in the way you use it the most
You might have a dictionary between questions and hashsets of students who chose certain answers, that way you can look up questions quickly, and find out who answered what, and get the count of each answer quickly.
Your above code might then look like:
void GetAnswerCountForQuestion(Question question, string answer) => Results[question][answer].Count;
Whether a student gave an answer:
void CheckStudentGaveAnswerToQuestion(Student student, Question question, string answer) => Results[question][answer].Contains(student);
Which answer a student gave:
string GetAnswerStudentGaveToQuestion(Student student, Question question)
{
foreach((string answer, HashSet<Student> students) in Results[question])
{
if (students.Contains(student))
return answer;
}
throw new ArgumentException($"{student} did not give an answer to {question}");
}
(with the caveat that there is no/limited error handling above)
this is impossible to sort your struct based on two values with same priority
you must decide the most "important" one (ie the value with highest priority in the comparator)
hey,
is there's a way to tell unity to write a shader script based on some bools or enums ?
for example
string line = default;
if( x == 1 ) {line = "
Tags
{"RenderType" = "Transparent" "Queue" = "Transparent"}
";}
else{
Tags
{"RenderType" = "Transparent" "Queue" = "Opaque "}
}
and then somehow ask unity to add the line to a script template ?
Sounds like something you'd use a database for.
And use something like sql to query whatever data in whatever form you need.
Thank you for the answers, I have to think about it for a while...
Sure. You can just read the shader source file and write to it like any other text file.
It might be better to look at the shader compilation pipeline though. There might be a way to hook to it in a more "organic" way.
Also you can just add both of these lines of code under a define, so that the compiler picks the right one based on the define value.
I guess the correct name is preprocessor directives.
And more specifically shader keywords
Okay, so, I'm fumbling through interfaces right now, and UnityEvents, and I wanted to make sure I was doing this right.
I have a base interface that my Transition Classes inherent from, here:
public interface ITransitionBase
{
//Holds events for completing a transition or detransition.
event UnityAction TransitionFinish;
event UnityAction DetransitionFinish;
//Holds functions for starting a transition or detransition.
void BeginTransition();
void BeginDetransition();
}
and then, to make sure that I can edit TransitionFinish and DetransitionFinish in editor, I've got this in my child classes:
//When the transition or detransition finishes, these are invoked.
public UnityEvent OnTransitionFinish;
public UnityEvent OnDetransitionFinish;
//Allows for Interface Functionality and Unity Editor functionality at the same time.
event UnityAction ITransitionBase.TransitionFinish
{
add => OnTransitionFinish.AddListener(value);
remove => OnTransitionFinish.RemoveListener(value);
}
event UnityAction ITransitionBase.DetransitionFinish
{
add => OnDetransitionFinish.AddListener(value);
remove => OnDetransitionFinish.RemoveListener(value);
}
So I can use something like Thingie.TransitionFinish += ThingToWatchFor, and have that added to the list of functions that will be fired when TransitionFinish happens.
I got most of this advice and explanations on how this works from ChatGPT, so I wanted to poke my head in here and ask around to make sure I wasn't just totally off the mark on how this all works.
As far as I can tell, I'm basically using using TransitionFinish as a gobetween for the exposed OnTransitionFinish UnityEvent that is visible in editor, so in code, I can treat TransitionFinish as if it were the same as OnTransitionFinish, right?
Did you try it out?
I wanted to make sure I understood the concepts first before I started trying to implement it/experimenting with it
I have a slight feeling that it's gonna be a compile error. That's why I asked.
it also makes no sense to me why you'd design it like this unless the add/remove behavior for each transition is different. It looks a lot like you're going to copy-paste those event implementations for each derived class instead of making your interface into a base class and implementing them there instead
See, that's why I came here to ask, because I didn't even consider the idea of using a base class instead of an interface.
So, if I made it a base class, like, "BaseTransitions", and had all my other transition classes inherent from it, I could make a List of BaseTransitions, and that list could contain the inheritors too, and apply the needed functions/events?
Yes you could have a list of them. You lost me with the apply thing though, what are you trying to do? Your base class would look something like this:
abstract class TransitionBase {
public UnityEvent TransitionFinish;
public UnityEvent DetransitionFinish;
public abstract void BeginTransition();
public abstract void BeginDetransition();
}
Derived classes would be forced to implement those two methods, or will be abstract themselves
Yeah, what I mean by apply is that I'm basically writing scripts that I can apply to stuff like a pause menu, so the pause menu can have a list of objects that need to transition in color or transform or whatever, so things turning invisible, sliding on screen, ect ect, and the idea is that each thing that needs to transition fires an event when it completes, which allows me to make the pause menu only actually pause the game once all the transitions are complete.
yes that'll work fine. If you're doing this in code, using UnityEvents is probably overkill and you'd be better off with a callback instead
sorry for late response but, it's not just two lines , i have like 30-40 lines
i need to make a script to write a template shader code based on parameter i gave it
then save that file to a local drive. maybe assets/shaders
Well, then just write as a text file then.
what ? how ?
Shader keywords is the right way to do this, whatever you're doing sounds messy and will be editor-only
i am making a shader tool , its not ment to be used as a shader but its meant to be used to create shaders , so its messy if we use it as a shader, but it's not if i only used the parts i want which is why i wanna write a new shader and based on parameter or keywords i could add those lines or not to the new shader.
System.IO.File
well good luck to you, for reference I would use shader keywords + custom shader GUI https://docs.unity3d.com/ScriptReference/ShaderGUI.html to implement what you're doing unless you actually are inserting some user text into the shader, but at that point you might as well just have your user edit the shader directly
could you give me an example ? i still dont know how I could tell script to create shader ?
do i need editor script or monobehaviour ? .. what should I look google ?
A shader is just a text file with the shader extension(for example .hlsl), so you just create a new text file normally, write the code text to it and name it "myShader.hlsl" or something. Check the System.IO.File API docs for the relevant functions(creating/reading/writing to file).
You can find many tutorials on writing and saving text files in C#.
The editor script can be whatever you want. It doesn't seem relevant to the question at hand.
alright , i think Its not as bad as i think its
@cosmic rain Thanks a lot ❤️
@mossy snow Thank you ❤️
The shader itself should expose the queues anyway on the material
pretty sure it's always exposed even
After some quick googling, I'm not sure what you mean. Is there some other way to do callbacks aside from UnityEvents?
you can use Action or define a delegate
gotcha. I want to be able to edit it in-editor, so I'll probably be sticking with UnityEvents, since this code is meant to be reusable for any kind of transitions (and events playing during them) I might need to do going forward.
Normal events, Action type, Func type
With some work you could support the other types, but UnityEvent is supported by default
Yeah. I know UnityEvents are apparently a bit more performance heavy, but all I'm using this for is for firing off functions when a transition or detransition ends, so there wouldn't ever be more than like ten of these happening on any given frame, and even that owuld be a bit obscene for this particular use
Well, they might be worse performance wise, but one thing you should remember is that c# is very optimized for anything
You could have a million events and the performance difference might not be noticeable
You're most likely never going to get to a point where you need to make compromises and leave out features for performance, so don't worry about it. Just be sure to properly use methods, and not do a million things every frame which could be done once for example
yeah, I'm just choosing UnityEvents over another callback method because UnityEvents are exposed in editor by default, so I can do more with them without needing to write new code, and reuse them more.
Get array of Sprites from Texture2D set as SpriteMode : Multiple ?
Okay, so, since my Item scriptableobject has a reference to a prefab, and that prefab has a script that holds the Item on it as well, I can't directly serialize my Item Inventory list to Json, (since it's a recursive thing).
Would it be better for me to make my inventory use item IDs that refer to a dictionary instead of being a list of the actual items, or making a serialization method that saves the list of ID's, then populates the list using the IDs when loading, (Or would it be better to do both?)
hey im back with my problem, both rt.rect.height and rt.sizeDelta.y return 0 probably because its grayed, is it possible to get this value?
well, yeah, it's being driven by a ContentSizeFitter
which is presumably on the same object
oh yes youre right, it turned out it need one frame to update rectTransform thats why it returned 0
but if you call LayoutRebuilder.ForceRebuildLayoutImmediate(rectTransform); before getting value, it will work
ah, yeah
I'm trying to make a deep copy that varies of level and condition through reflection and i'm having problems with arrays. 
don't crosspost
It's beginner. I'll delete the first. 
the arrays. 
What's the site for posting code again?
!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 should probably ask what you're trying to accomplish here
not "deep copy via reflection"
what are you trying to accomplish with this?
Deep copy using reflection with varying levels of deepness and condition.
did you read what i just posted?
i want to know what you are going to do with this
there might be a simpler alternative
what game feature are you creating here?
Hmmm, i often go to far with these.
But what i do need atm is to duplicate an element for a Scriptable Object.
My other deep copy code i got off off internet doesn't work with UnityEngine.Color.
"duplicate an element"?
if you make the class serializable, you could just serialize and deserialize it to get a copy
Wait a sec. 
[Serializable]
internal class DebugTriggerMechanics : BaseTriggerMechanics
{
[Header("Components")]
[SerializeField] private string str_message;
[SerializeField] private Color debug_colour;
protected override void ActrivateTrigger(in Vector2 origin, Vector2 facing_direction, Vector2 facing_point)
{
if (str_message != "") Debug.Log(str_message);
}
}
Yeah.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0063:Use simple 'using' statement", Justification = "<Pending>")]
public static T DeepCopy<T>(T other) where T : class
{
using (MemoryStream ms = new())
{
BinaryFormatter formatter = new();
formatter.Serialize(ms, other);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
hm, I suppose there's some kind of distinction between "serializable by the unity editor" and "serializable in the eyes ofthe BinaryFormatter"
hi i made my first game everything seems to work well on the pc but once i put it onto android the buttons in the main menu no longer work. Heres the code for the buttons for reference https://gdl.space/bevizibito.cpp
Have you used Android LogCat to debug the problem?
I'm trying to expose a method in the inspector with [ContextMenu("MethodName")]
I want to call a [Serializable] class' method from a monobehavior containing this class, is this possible as is or will I need custom editors? Or can I create the [ContextMenu] in the containing class to call this function?
so you have a nested class?
and you want to call a non-static method on that nested class?
What is ContextMenuItem?
it lets you invoke a method on the MonoBehaviour from the inspector
Looks like the constructor needs two parameters
not sure about the meaning of nested class, but to clarify :
public class Units:Monobehaviour{
public Stats stats;
}
public class Stats {
[ContextMenu("UpdateAllstats")]
public void UpdateAllStats(){
//...
}
I know if I use [ContextMenu] in the Units class it shows in right click menu in inspector but is there a way to make it access the stats class methods from Stats within Units
Just read the docs/examples
i've used it a few times before
Space goes on fields
My bad meant to write ContextMenu not ContextMenuItem hence the red line
Attributes are never standalone
oh wait, you're right. what am i on about.
I already used ContextMenu to call methods from inspector
Never made it work with args
I just figured that it was configured to work when applied to fields, methods, etc.
I must have actually had it on a field and just not noticed.
ah! yes, this makes more sense now.
that's what I used
that attribute goes on a method.
the attribute must be attached to a method on the MonoBehaviour.
i'm still unclear what you want to do
you can't just call a method on a nested class -- you don't have a specific instance of that class to call the method on
you can, however, call a method on the MonoBehaviour that manipulates an instance of the nested class
Ok so it needs to be on the monobehaviour, cant put it in the Stats class so that every monobehaviour ( or SO) I attach it tohas the contextmenu option
Not that I'm aware of.
Can't make a custom editor for your SO ?
Are there gonna be some alternatives?
Seems like i'm having a hard time working on deep copy with reflection too. Like i don't know how i'm gonna go about it.

how do i fix this ?
weird internal error in the visual studio package, hm
i'd hit it with a reimport-all to start
go to the project window, right click, Reimport All
THIS ?
Yes, that also works
you may need to update a package
i'd hit Ignore and then check Window > Package Manager
unsure
hmm onParticleCollision isn't working
in that what to upgrade ?
you would want to look at the Visual Studio package
it isn't ever logging anything, no matter where I put it
ok
well, it sounds like NetworkManagerHelper uses it...
Any reason or exampling on how to properly use OnParticleCollision?
because It refuses to work for me
where should I put the script with OnParticleCollision for it to detect collison
no, that is used to get the full list of collisions
ok then
it can't be necessary for the message to get sent in the first place
private void OnParticleCollision(GameObject other)
{
Debug.Log("Working");
}
and where did you put the MonoBehaviour that this is a part of?
I have this basic to test
but the message never shows
ive tried it on both the hit collider and the same script that is used on the particle maker object
nothing
i'm pretty sure you have to turn on collisions in the particle system
rofl @heady iris your past self is not helping me at all ! 🤣 (was searching for my problem on the discord, found this haha)
so any reason why it never triggers? This is very bafffling to me
it will not say "Mixed" if you have every single layer selected
odd
Hello!
I've started using Unity Splines package. There is not a lot of information on the internet. Has anyone done any significant work with this package? I'm trying to connect two objects with a spline that should behave similarly to how nodes and connections work in ShaderGraph or Visual Scripting. My expectation is that Unity spline would change its shape when, lets say, last node is moved (bend along with it). But it really bends only the last segment.
this is most strange
The particles needed to be meshes, not billboards. I settled on using Quad meshes for them, since I just need effectively 2D sprites.
Ohhhh
ok
Ah. That would do it.
okay, so, I'm having a weird issue
specifically, I'm having an issue figuring out what the issue even is
clearly, there is an error of some kind
I'm getting these errors on runtime, but I can't actually track down what's causing them. None of my scripts show any errors in visual studio, the errors themselves don't say what script or object is calling them, so
This looks like an error in the inspector.
or in some other chunk of editor UI
i would start by restarting the editor
Hi. I have 2d simple mesh. How to convert this mesh to sprite asset?
Gotcha
take a screenshot of it
not at runtime, right?
if so, I'd just render it out in Blender
you can turn on transparency so that the background isn't opaque
If these are runtime errors you need to ask yourself why are they running Editor code
yes, not a rantime. I slice 2d apple image mesh to several meshes and now i want to save this part as sprite assets and add it to scriptable object Parts with unique ID.
in unity
I've seen situations where the editor throws up only while the game is running
witout blender
yeah
now no errors are being thrown up
now that I've restarted the editor
thank you for the advice! I suppose something just gets confused in my editor over time?
I often see this in the form of errors in a graph editor
something gets lost due to some subtle (or maybe flagrant) design error
and then it just falls over and dies
Hmm.
After some experimentation
the errors seem to crop up around my SerializedObjects. I just got an error thrown when I:
- Started runtime
- Saved a file
- Exited runtime
- Entered Runtime again (The save list, which is a scriptable object, is updated)
- Error thrown:
does it depend on what you are inspecting?
No. It's explicitly thrown when I start runtime, and only once.
let me see if I can replicate it
and if I can, I'll share the code that might be causing it?
Hmm. So adding ANOTHER new save file didn't result in a second error being thrown, still just the one singular one.
still, I'll make a paste of my Savelist code and post it
maybe someone here will see whatever it is I'm doing wrong
how to set Color in this format?
R [0 - 255]; G [0 - 255]; B [0 - 255]; A [0 - 1]
Each color component is a floating point value with a range from 0 to 1. (UnityEngine.Color)
Here's the code that MIGHT be causing it? if nothing jumps out at anyone, I'll have another poke around to see if I can get something else
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
this is just an alternative way of letting you edit the usual Color struct
there IS Color32
which stores the R/G/B/A components as bytes
thus, 0-255
thank you )
Color32 can implicitly convert to Color, so you can use it anywhere that wants a Color
but there's not a huge reason to do that, unless you really specifically need to use the familiar 0-255 range
it's so-named because it's a 32-bit color
rather than Color, which uses 128 bits in total (32 per float channel)
I'll ignore it
does anyone know how to disable scrolling by player in TMP_InputField (or InputField) ?
input.verticalScrollbar.enabled = false;
?
there's no scrollbar I gues
oh, yeah, I am sorry, it does
but it does not work
what do you mean?
yeah just noticed
which scrollbar do you see? i never noticed one on InputField
Hello everyone !
Is there a way, from a script attached to an GameObject, to clone the GameObject ?
(looking on google, I mostly find things about cloning and duplicating in the interface).
Is this actually correct ???
GameObject clone = Instantiate(gameObject);
you can scroll InputField, but yes, there is no scrollbar
so if there is lots of text
yes, just get instance of the gameObject and Instantiate is
OK, I'm so used to instantiate "clean" Prefabs, I didn't think about using it that way
depends where you call this, it can probably cause an issue with infinite loop
example if it's put in Start it will keep cloning itself infinitely
if it is in while loop, yes
no without while lol
yeah, not putting something like this in the start method 🙂
I see, it instantiates itself with a script that instantiates itself with a script that instantiates itself with a script that instantiates itself with a script that instantiates itself with a script that instantiates itself with a script that instantiates itself with a script that instantiates itself with a script that instantiates itself with a script that instantiates itself...
we call that Recursion 🙂
Use invokeRepeating to controle the spawn ratr
recurstion is when the script calls itself ??
i don't shink that's recursion
private int Nice(int bla)
{
bla += 1;
return Nice(bla);
}
Recursion is recursion
funny fact, if you type recursion in google it keeps asking
Did you mean to search for: recursion
you keep clicking it and keeps showing it
small giggle
this would give you compile error
🙄
nope.
No argument that correspond to required parameter or sum like that
yup
looks fine to me.
Is there a method to just grab a random location inside of the biggest circle?
the circle is a collider(trigger)
ah
nope, you have just not seen it 🙄 for sure
dammit, beat me to it
i was finding your post 😛
xD
i was searching for "Annular"
ah, I can just grab the colliders radius and use that 😄
thx
Is that a bad way to do a "radius" for like a mob spawner?
why would it be bad ?
figure having a way to visually see the radius is good
cause the only purpose of the collider is to visually see the spawn radius lol
for hard arithmetic figures you can spawn random point like in rectangle until this point is nice for you
you could use editor gizmos to draw the radius without actually sticking a collider on it
this is a good strategy for weird shapes, yeah
rejection sampling!
noooo you can't just uniformly sample points until you find a good one, you have to do complex math! noooooo!
haha rectangle go brr
That requires the game to be running to show up right?
No. Editor gizmos appear in the scene view.
Good to know thx
I mean, they can appear in the game view, too, if you turn on gizmos
i believe they don't show up in the built game
yup gizmos is editor only
Makes sense, Ive used it before but had to click play to see the gismos...maybe I was using them wrong lol
you prob were using the Debug.Draw functions
Ah yeah you are right
I bet they still work in editor scripts
but yeah, your code was only running in play mode
Gizmos are a little different. They're drawn in specific functions
i think they both call DrawLine_Injected
interesting call to C++ I guess for both
private static extern void DrawLine_Injected (ref Vector3 from, ref Vector3 to);
passing vector3s by ref. wacky!
I added Shape.Annulus to my debugging package the last release, and its functions can be called from anywhere so it's handy https://github.com/vertxxyz/Vertx.Debugging
noice!
bookmark this
neat
ah, it was added then?
it shouldn't really be necessary if unity is correctly noticing file changes
Has anyone ever encountered the issue where OnPointerDown event does not trigger while the timescale of the game is 0, but only if the gameObject was instantiated while the timescale is 0? If the timescale goes back to normal and then back to 0, the event still works. If so, has anyone any pointers as to how I could still register the OnPointerDown event for a gameObject while it is instantiated in timescale 0, and the timescale is still 0 when trying to press it?
Does anyone know if it is possible to get the coroutine from inside of itself? Like a "this" keyword but for coroutines
what’s the use case?
Because I want to assign a coroutine that is being called from another script to a coroutine variable inside of its own script
and I don't want to have to have a coroutine property with a public set
can you assign the reference before you start the coroutine someVar = StartCoroutine(A());, or does it need to be assigned after you started it?
It can be assigned like that but that means in my use case every time I want to call it, which it is only called from another script, I have to assign it to a property from it's home script
I can do it that way I was just wondering if there is a better way, like assigning the coroutine to a coroutine variable from inside of itself when it starts running somehow
Coroutine cor = StartCoroutine(MyMethod(cor));
oh, I could pass it in as a parameter
that's a good idea
Now I don't have to have another public member of my script for no good reason. Thanks
I read this article about dependency injection, wondering if I should implement it yourself. The way he implements it is having a dependency context MonoBehaviour inject its children and also putting itself in DontDestroyOnLoad. Is that really the best way to do it? Isn't the point of DI to have any class be able to access dependencies to replace singletons, not just children of a DDOL manager??
yield return new WaitUntil(() => activeEnemies.Count == 0);
How often will this code check this? Is this bad to use inside a coroutine if many objects will have it?
it's checked twice per frame, iirc
around Update and LateUpdate
you'd find that if you checked the docs :p
if all of the objects have the same condition, you can have just one have that coroutine that’ll notify the rest once it’s finished
Is the count check expensive at all though?
define expensive?
the check itself is just checking the count of a list
however the fact that its checking once every frame is bad right?
not really
How much better is a WaitForSeconds?
computers can do a LOT of work
but it’s an easy optimization. Especially with lots of enemies
they do different things
Doesn't it check the time atleast once a frame?
unfortunately my case all spawners have this and are keeping track of their own spawns
so can't really use 1 coroutine to check for all
ah i see, so they all have different ones
yep
Im curious about this now 😄
would have expected the WaitForSeconds to be much better, now Im not sure at all lol
You should at least cache it, to avoid creating a new WaitForSeconds each time
you can, indeed, re-use the same instance many times
yes, they do, whichever yield wait you use the bool condition has to be evaluated at least once per frame
Something like this https://hatebin.com/cwhkrkimml
WaitUntil EnemyCountWait=> activeEnemies.Count==0;
Unity gets mad if I try and cache it like this...how could I try and cache it?
Caching the WaitUntil shouldn't be neccessary, but it would be
readonly WaitUntil EnemyCountWait = new WaitUntil(() => activeEnemies.Count==0);
didn't you recommend to cache it above?
I have copypasted the full code from TMP_InputField to another script and renamed TMP_InputField class to CustomInputField.
But in the Inspector some components are missing and also shifted a bit.
dangerous to cache a WaitUnitl, WaitForSeconds however is a different matter
good to know thanks
Right, it has to be a local variable
(inside the method)
which defeats the purpose of caching it
is using a "new WaitUntil(list.count ==0) better, worse, the same than a cached (or does it not matter) WaitForSeconds(0.5f)
not sure if Im overthinking it 😄
worse
I think the difference is extremely small
but yes, you are overthinking
fair enough
Why is caching a WaitUntil bad?
private List<GameObject> activeEnemies = new List<GameObject>(); // List to track active enemies
private WaitUntil allEnemiesDestroyed;
// Start is called before the first frame update
void Start()
{
allEnemiesDestroyed = new WaitUntil(() => activeEnemies.Count == 0);
StartCoroutine(spawnEnemy(ghostSpawnRate, ghostPrefab));
}
seems like it would work nicely
It only uses one WaitUntil per coroutine
So if you're only running it once, the caching does nothing
hello! i'm new here
activeEnemies is, in this case a class varaible. generally with WaitUntil you would require a local variable
so that means......in this case it isn't bad/dangerous to cache the waitUntil?
correct
but it gains you nothing by doing so
figure it prevents a new one from being created every frame?
thus saving at least a little performance?
interesting
I wonder why WaitForSeconds is different then
sounds like Unity is just caching the waitUntil itself
because it can easily be shared between many coroutines
I understand like 70% of that lol...but good enough for me 😄
no need to cache waitUntil, but do cache WaitForSeconds 🙂
this is created once
WaitUntil(() => activeEnemies.Count == 0);
this is evaluated once per frame
() => activeEnemies.Count == 0;
But the above where its cached isn't better than this?
yield return new WaitUntil(() => activeEnemies.Count == 0);
not as you used it, no
gotcha thanks 🙂
if your startcoroutine was in a for loop for example then caching the waituntil would make sense
So if I was in a while(true) loop like this caching it is good right
private IEnumerator SpawnEnemy(float interval, GameObject enemy)
{
while (true)
{
// Check if the maximum number of enemies has been reached
if (spawnedEnemies >= maxEnemies)
{
// Wait until all active enemies are destroyed
yield return new WaitUntil(() => activeEnemies.Count == 0);
// Reset the counter
spawnedEnemies = 0;
}
yield return new WaitForSeconds(interval);
GameObject spawnedEnemy = Instantiate(enemy, new Vector3(Random.Range(-spawnSquare, spawnSquare) + transform.position.x, Random.Range(-spawnSquare, spawnSquare) + transform.position.y, 0), Quaternion.identity);
// Add the spawned enemy to the active enemies list
activeEnemies.Add(spawnedEnemy);
spawnedEnemies++;
spawnedEnemy.GetComponent<EnemyController>().OnEnemyDestroyed += RemoveEnemyFromList;
}
}
yes, that would be a very minor improvement
but overall WaitUntil and WaitForSeconds improvement is small enough I can do whichever I prefer as well
had thought that caching things like WaitForSeconds and WaitUntil would be mediocre improvements always worth doing 😄
again it depends how often they are being called, like everything else. No need to optimise to the nth degree something which is only being executed once
Makes sense to me, Thanks for all the help!
np, good to see you are at least thinking about these things because they do matter
out of curiousity...do you have a link to the stuff you have put on the unity store? notice that I can't find a "SteveSmith" by looking it up 😄
Unity hate me
there is also
https://stevesmith.software/
Does anyone know what happens to a coroutine value when the coroutine it represents stops running?
nothing
Like if I say Coroutine c = StartCoroutine(coroutine()); What is the value of c when coroutine() stops running on its own?
the value given to it by the startcoroutine. not that you can do anything with it
Also what happens if I call StopCoroutine on c
depends if c is running
yeah, so what happens if I try to stop it and its not running?
pretty sure absolutely nothing
ok, thanks
is there a lightweight queue I can use in update method?
I feel the C# queue is heavy, though idk really
takes up a lot of cpu cycles to dequeue/check
standard library data structures are pretty performant
don't try to prematurely optimize
If there's anything you need to worry about Queue, its allocation when creating it and when enqueuing many items.
your computer's CPU is screaming along at billions of cycles per second
you can remove an item from a queue
don't think about it.
ok
I mostly allocate tuples into the queue
they contain game objects and some parameters, like a vec3
You can create a queue with a predefined capacity.
dequeue is O(1) operation and you can see how they dequeue
https://referencesource.microsoft.com/#system/compmod/system/collections/generic/queue.cs
Given that the capacity is not exceeded.
dequeue
Oh, yeah my bad.
I was reading enqueue at the same time.
If Count already equals the capacity, the capacity of the Queue<T> is increased by automatically reallocating the internal array, and the existing elements are copied to the new array before the new element is added.
If Count is less than the capacity of the internal array, this method is an O(1) operation. If the internal array needs to be reallocated to accommodate the new element, this method becomes an O(n) operation, where n is Count.
I use TryDequeue
and I want my capacity to be very high, so not putting a limit should be fine
It is the inverse
You want to put a capacity before hand to reduce the amount of time you reallocate memory.
generally for allocation strategy of doubling the size, the avaerage time of adding one element is O(1)
if you want to absolutely wring out every last bit of performance, then you want to preemptively give the queue a high enough capacity
Capacity is the initial allocation.
of course, this probably doesn't matter at all
right
this is also server side code
tickrate will be around 30-45
so I think it will have ample time to dequeue
and do gc at the same time
Your issue will most likely NOT be a queue if you ever have one.
write the code normally, then profile it if you need to
yeah I will
you can set the initial capacity to be a power of 2 so that each % will be turned into & operation (i remember the initial capacity is 4)
i sometime do this
then set it to 64
How many of those queues are you creating every frame?
it's a class level queue
created once per script
%power of 2 is equivalent to & power of 2 -1
but these optimization will be handled by compiler
Then why are you even talking about optimization? This is a total waste of time.
I was asking if dequeuing was an expensive operation
it’s practically free, that’s the whole point of a queue
👍
i dont know, but for compile time const the compiler is supposed to generate bitwise and if the queue size is power of 2
all of this is going to be a rounding error in the grand scheme of things
yup
why does he write that there are 6 triangles if there are 2 triangles in the quad?
hi,
is there is a way to replace something within a text file after reading it ?
example
txt file , Name txtFile.txt
var x = [X];
is it possible to read the file using string[] lines = File.ReadAllLines(filepath);
then somehow search for all [X] and replace it with 10; ?
Each triangle consists of 3 indices that point to a vertex in the array
So each item in triangles is actually 1/3 of a triangle
and supposedly in a row they just go X Y Z X Y Z?
No they are not XYZ coordinates
They are indices for the vertices array which contains the coordinates
aaa of course
How i can disable the AR Plane that its placed ? i use ```cs
plane.requestedDetectionMode = UnityEngine.XR.ARSubsystems.PlaneDetectionMode.None;
private void SubdivideMesh()
{
MeshFilter meshFilter = GetComponent<MeshFilter>();
Mesh originalMesh = meshFilter.sharedMesh;
Vector3[] originalVertices = originalMesh.vertices;
int[] originalTriangles = originalMesh.triangles;
Vector3[] newVertices = new Vector3[originalVertices.Length + (originalTriangles.Length / 3) * 3];
int[] newTriangles = new int[originalTriangles.Length * 4];
for (int i = 0; i < originalTriangles.Length; i += 3)
{
int vertIndexA = originalTriangles[i];
int vertIndexB = originalTriangles[i + 1];
int vertIndexC = originalTriangles[i + 2];
Vector3 vertexA = originalVertices[vertIndexA];
Vector3 vertexB = originalVertices[vertIndexB];
Vector3 vertexC = originalVertices[vertIndexC];
int newVertIndex = i * 4;
newVertices[newVertIndex] = vertexA;
newVertices[newVertIndex + 1] = vertexB;
newVertices[newVertIndex + 2] = vertexC;
newVertices[newVertIndex + 3] = (vertexA + vertexB + vertexC) / 3f;
newTriangles[i * 4] = newVertIndex;
newTriangles[i * 4 + 1] = newVertIndex + 1;
newTriangles[i * 4 + 2] = newVertIndex + 3;
newTriangles[i * 4 + 3] = newVertIndex + 1;
newTriangles[i * 4 + 4] = newVertIndex + 2;
newTriangles[i * 4 + 5] = newVertIndex + 3;
newTriangles[i * 4 + 6] = newVertIndex + 2;
newTriangles[i * 4 + 7] = newVertIndex;
newTriangles[i * 4 + 8] = newVertIndex + 3;
newTriangles[i * 4 + 9] = newVertIndex;
newTriangles[i * 4 + 10] = newVertIndex + 2;
newTriangles[i * 4 + 11] = newVertIndex + 1;
}
Mesh subdividedMesh = new Mesh();
subdividedMesh.vertices = newVertices;
subdividedMesh.triangles = newTriangles;
meshFilter.sharedMesh = subdividedMesh;
}
why this code not change my mesh in mesh filter?
meshFilter.mesh = subdividedMesh;
but originslMesh is sharedMesh?
yes, I know
hmm
sharedMesh and mesh are 2 different things. Read the docs
The SharedMesh property refers to your actual mesh asset, so changes to the mesh will affect all objects that use that mesh reference, and (I think) changes will apply to the mesh asset in your asset folder with running in-editor.
The Mesh property will apply to the "mesh instance" created for this specific object. The first time you access the "mesh" on an object, a new copy of the mesh will be created for you to modify. All additional times you access the "mesh" on the same object, you will get the same mesh that was created for you the first time you tried to access the "mesh" on this object. Since each object has it's own instance, edits will only apply to the one object.
Yes, i Read this, but with sharedMesh should also work
this line doesn't work either
heya, im learning tilemaps with composite colliders, previously I had seperate gameobjects for every floor and wall.
I'm running into a problem where my character's Y velocity is never zero when it is on the tilemap floor, which is important for other code I have written. this problem is fixed when i set the tilemap's rigidbody2D to dynamic, but i'm assuming that's bad practice for stationary platforms. I didn't have this problem when I used individual gameobjects set to static. could I have some help?
Hey Guys, I have a Question !
I did this code that is supposed to check if it is a single tap or a swipe but it doesn't work. Could you help me ? ```
private void Start()
{
touchControl.Earth.EarthX.started += UpdateRotation;
touchControl.Earth.EarthClick.started += OnClickStarted;
touchControl.Earth.EarthClick.performed += OnClickPerformed;
}
private void UpdateRotation(InputAction.CallbackContext context)
{
Debug.Log("Swipe");
float earthXValue = context.ReadValue<float>();
float rotationAmount = earthXValue * rotationSpeed * Time.deltaTime;
transform.Rotate(0f, 0f, -rotationAmount);
}
private void OnClickStarted(InputAction.CallbackContext context)
{
clickStartPosition = context.ReadValue<Vector2>();
}
private void OnClickPerformed(InputAction.CallbackContext context)
{
Vector2 clickEndPosition = context.ReadValue<Vector2>();
touchControl.Earth.EarthClick.performed -= OnClickPerformed;
Debug.Log("test");
if (Vector2.Distance(clickStartPosition, clickEndPosition) <= clickPositionThreshold)
{
Debug.Log("Tap");
}
}
}```
!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.
Im trying to make like a 2d sandbox and there are different types of Tiles like Stone and Dirt each represented by their own class extending a Tile class
what would be the best way to replace a Tile? i have like 2 methods for Deleting a Tile and placing a new one
but when replacing a Tile i could get away without deleting and creating a new GameObecjt, right?
use tilemap?
and try this https://docs.unity3d.com/ScriptReference/Pool.ObjectPool_1.html
@tiny reef
ill have a look thx
Got a weird bug with some gameobjects not invoking their OnMouseDown's when I change to a different camera. For context, I have 2 cameras, one renders a minigame, which turns off the main camera and enables the minigame cam until the minigame is over. Then the main cam is enabled again, but gameobjects within the main cam can't be clicked on unless (discovered this) I enable and then re-disable either one of the cameras
I troubleshot so far as to disable everything inside the minigame besides the camera, and it still happens
I don't understand why enabling/disabling a camera would make the gameobject clickable again. I'm literally not changing anything--so it must be something Unity does under the hood that causes this
OnMouseDown most likely depends on the "Main Camera", though this is not really clear or documented.
It'd be better to use the newer, more documented and more flexible IPointerDownHandler
which will depend on which camera has an active PhysicsRaycaster
i was wondering about that
Will this work with BoxCollider2D?
These are normal gameobjects with normal transforms, not UI elements with a rect transform on a canvas
Yes with a Physics2DRaycaster
The only difference between doing this with UI and game world objects is which Raycaster
GraphicRaycaster on the canvas for UI
PhysicsRaycaster (2D) on the camera for game world colliders
Ok, I created a new scene and attached physics2DRaycaster to the camera. Added an event system and a test script that implements IPointerDownHandler, IPointerEnterHandler, IPointerUpHandler, and it won't detect a touch on the box collider 2D in the scene.
which object did you attach the script to?
My test script that implements the handlers is attached to the same gameobject that has the box collider 2D
event system is attached to a separate empty gameobject
I've never gotten those handlers to work without a canvas
I'd be delighted if it was possible
does the event system have the appropriate input module?
This is indeed the whole point of the physics raycasters
which wouldn't exist if it were not possible
is the camera and/or gameobject that has the raycaster enabled too?
Hi hi! I'm having some problems with Newtonsoft. Currently it is serializing the data just fine, but deserialization is giving me some issues (that didn't happen before tbh).
So it says Unable to find a constructor to use for type Core.Survivor.SurvivorData
thing is it does have one:
namespace Core.Data
{
[Serializable]
internal class SurvivorData
{
[JsonProperty] public List<Survivor.SurvivorData> survivors = new List<Survivor.SurvivorData>();
[JsonProperty] public List<Vector3> survivorsPos = new List<Vector3>();
[JsonConstructor] public SurvivorData() {}
//[JsonProperty] public Dictionary<Survivor.SurvivorData, Vector3> survivors = new Dictionary<Survivor.SurvivorData, Vector3> ();
}
}```
any idea what's going on? 
go to #archived-shaders
it seems that it requires your class to have a, well, constructor method
public SurvivorData() {}
should fix the issue
thanks, didn't notice that it exists
[JsonConstructor] public SurvivorData() {} in case you didn't notice, it has one 
oh, right
hmm
maybe it requires a constructor with a certain set of arguments? but the error for that should be different iirc
shouldn't be an issue. The class handling this data also has a default constructor and is populated with the deserialization. For some reason it isn't liking this class too much
the error is for Core.Survivor.SurvivorData and the code you showed is Core.Data.SurvivorData
different class entirely
Kinda confusing that you have those two classes with the same names AND this one contains a list of the other one 😵💫
one was made by me for data handling, the other one was made by my partner (idk why he would call it survivorData as well
)
but i think it won't fix my issue i think lemme try some stuff
i mean the issue is that Core.Survivor.SurvivorData doesn't have an appropriate constructor
the fix is to give it one
it does have a constructor i think i forgot to pass the attribute on it, but even so it won't work the way i want possibly, maybe i'll have to do some changes
not one that Newtonsoft can use, is the thing
yeah the attribute does wipe the error
but yes you might have to refactor some things
actually worked without a refactor
isnt it an issue too that its internal or no?
nah, that has to do with access levels based on being under a namespace
you can have a private class and deserialize into it as long as whatever you're deserializing to is public and matching names afaik
you can say internal = public, but internal is only visible inside the same assembly, plus namespaced classes are by default internal, which are public.
it's just small nuances
correct me if i'm wrong tho 
internal has only to do with assemblies. Namespaces aren't involved.
classes are only internal if they're marked as such. The default access modifier is private
i meant like when you create a class under a namespace it comes automatically as internal for me tho
i know how internal works, i just was questioning if it would cause Newtonsoft from finding it
but if its not the issue then disregard
That might just be an IDE feature dunno
possibly, but yeah, using the snippet will come as private, but idk why all my namespaced classes get internal
either way i just got used to it unless i really need to force them to be private
Have you faced situations where you define attributes (Attribute type) for each attribute of a scriptable object instead of defining primitive types like int Power, int maxHealth?
I mean wrap attributes inside Attribute type, encapsulate it.
public class AttributeDefinition : ScriptableObject
{
public string Name;
public Sprite Icon;
}
public abstract class Attribute
{
public AttributeDefinition Definition;
public abstract string StringValue { get; }
}
[Serializable]
public class Attribute<T> : Attribute
{
public T Value;
public override string StringValue => Value.ToString();
}
[Serializable]
public class FloatAttribute : Attribute<float>
{
}
[Serializable]
public class IntAttribute : Attribute<int>
{
}
public abstract class Data : ScriptableObject
{
public abstract Attribute[] GetAttributes();
}
public class Data1 : Data
{
public IntAttribute Power;
//...
public override Attribute[] GetAttributes()
{
}
}
public class Data2 : Data // Data1 and Data2 are completely different types
{
//...
public IntAttribute Power;
//...
public override Attribute[] GetAttributes()
{
return new[] { Power };
}
//...
}
The benefit is that you define an attribute only once (name + icon), then you can use it in different unrelated scriptable objects. Also, getting attribute info is easy to show them as stats.
or you prefer to define attributes of scriptable objects explicitely with primitive types and then inside UI classes, handle how they should be shown (probably different UI class for each),
public class Data1
{
public int Power;
//...
}
why is it when i use instantiate on a prefab, its position is always 0, 0, 0 no matter what?
#💻┃code-beginner and show what how you are instantiating it
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
are u specifying that it should spawn elsewhere, or just hoping it knows where to spawn by itself?
My guess would be that you're probably checking the position of the prefab rather than the clone.
Or you're just spawning it at 0,0,0
I use Vector3.SignedAngle()
blue line is the axis
but why it returns 50?
I don't understand
It's hard to tell what you are doing, it would be easier if you provided some code
result = Vector3.SignedAngle(Vector3.down, transform.rotation * Vector3.down, transform.rotation * Vector3.forward);
I would replace transform rotation to gyro.attitude
Just a gotcha about SignedAngle:
Do not expect the "from" and "to" vectors to be flattened against the Axis when calculating the angle. If the inputs are pointing at all up or down in the plane defined by the axis, you're going to get the "Angle between two 3D vectors" returned. NOT the "Angle between two 3D vectors flattened on a plane".
Workaround: Make sure that you flatten the "from" and "to" vectors against the axis: i.e.
Vector3.SignedAngle(Vector3.ProjectOnNormal(from, Vector3.up), Vector3.ProjectOnNormal(to, Vector3.up), Vector3.up);
(this is a comment on the docs made using my extension (https://github.com/Developer-Notes-Extension))
welp, someone needs to make this more clear then
Yeah, the axis only influences the sign, nothing else
Vector3.ProjectOnNormal doesn't exist for some reason
ProjectOnPlane will do it
oh ok
let's see
the X axis affects the sign of the result
found the problem
now it just affects the result
oh wait no
I rotated it locally in the scene view
it works perfectly now
thanks alot
Using the Lobby Services, how can you get how many people are in the lobby?
tyy!
!codebin
📃 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 posted this on Reddit however I didn't get any responses so gonna post the link here with a summary. https://www.reddit.com/r/Unity3D/comments/13ulgis/portals_rendering_characters_advice/
I'm working with Sebastian Lague's code base for portals in my shooter and I'm unsure how to proceed with how to render the Player's third person model when viewed through a portal. In his codebase, a clone object of the players model is created to mimic the player moving through a portal seamlessly.
My issue is that when the Player clips into a portal partially, the 3rd person clone object gets rendered on the exit portal which can block the view in return ruins the seamless effect. I'm not asking for code but advice on how to tackle this issue as I'm probably overthinking it. The reddit post lists all the things I've considered/attempted so far however I'm unsure which is the best route to go unless I've missed a obvious one.
I'm not entirely sure I understand your setup, but in first person games, you would usually not render the third person model in the first person camera, using layers to cull it.
Ah, I think I understand the purpose of rendering that model by your first person camera!
Or not.
Yeah, I guess I still don't understand why you'd need the third person model sticking to your first person camera.
Just to clarify, In Portal, you can see the player character through portals. My setup, the first person camera doesn't render the player model however the portal camera do render the player model
Anyone great with tilemaps? My game uses 960x540 as the Pixel Perfect reference resolution, and I want my overworld tiles to be 60x60. By default that means my grid hangs half a tile out of screen, so I figured no problem, I'll just offset it 30 pixels. Unfortunately, now when I place a tile, it gets a 30 pixel offset, despite having {0,0} offset when I select it in the palette
should I post a recording of the issue? I'm probably not explaining the issue well
I see. What if you offset the model back behind the fps camera a little bit?
I'll give that a try. that could be the simple fix I overlooked
doesn't work unfortunately. Offsetting the character moves the clone object out of the view on the otherside causing the player to be partially cut off. didn't find any middle ground with the offset. Thanks for the suggestion though
What's better for damage particles, start a particle system inside the enemy or instantiate it on hit?
Instantiate on hit would definitely be easier and the preferred option I imo. Since you are using particles, you could replicate the particles spawning from inside the mesh without needing to spawn them inside the mesh. What kind of damage is this? Bullets, melee damage?
id assume, on hit no?
How to get all pixels from texture that used in my mesh triangles? I vant save this part pf texture as sprite
Melee, also have the bullet one but I'm using the same particles because of the nature of the proyect
So all the mesh triangles or just the ones that are currently rendered?
Checking if a non-http link is valid
Anyone know how to check if a link is valid in unity?
I know you can use:
Application.OpenURL(someLink);
but the problem is that doesn't return anything to tell you if the link is valid or not and give you a way to habdle what to do if it isn't valid
I made this little extension:
public static bool IsValidURL(this string source) => Uri.IsWellFormedUriString(source, UriKind.RelativeOrAbsolute);
and that works fine if you link starts with "https://" like this for example:
"https://www.google.co.za/"
But if I want to open a link in the browser that isn't an http link, like say for example a repository URL:
git@ssh.dev.azure.com:v3/SomeOrganization/SomeProjectProductName
The IsValidURL extension will return false because it's not an HTTP link
only those that are rendered
That only makes it harder, a lot harder I think. What is the deal with all this? I think this is a xy problem at this point, theres probably better way to achieve the same thing
I write some code, but it work not correctly https://pastebin.com/7MT79YRg
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Wait no, I meant if its a 3d model that you can view from any side, do you want only the visible pixels to be added to the texture?
I want only convert simple 2d meshes
Maybe your triangle rasterization is flawed in some way. If the processing speed is not a concern for you at this point, you could just take the bounding box of the triangle, loop through each pixel on the box and use algorithm copied from online to check whether the point is inside the triangle or not, just to make sure its not the scanline algorithm thats failing (scanline algorithm sounds fine, id use something like that myself too)
I don’t understand a little what is wrong in my algorithm, and why a black spot with holes is formed
I don't care about speed, it's just for the editor
Thats why Id definitely switch to much faster to implement algorithm to verify your algorithm is not working and maybe even use that if the speed is not a problem
What other algorithms are there for this problem?
I explained one here
Just different way to rasterize the triangle
are you sure you aren't overcomplicating this? If you're just trying to capture what the mesh looks like into a texture, why not set up a camera + RT, render mesh, then just read pixels straight back? Pixel-by-pixel rasteration looks crazy. The other simple thing you might try is to literally create a sprite and copy the mesh data to it, UVs and all, and save that as an asset. I haven't tried that, but I assume it would work too
i want to use these sprites in game later, i don't want to use render texture and camera
you said it was editor only, so why does that matter? Create the sprite as an asset
yes, than use this part of image in runtime as sprite
the problem is that the texture itself is superimposed only by a certain part on the mesh, somehow I didn’t figure out how to copy the visible part of the mesh just into a sprite
My game requires procedural generation, where tiles need to be placed and modified at runtime so i think a tilemap wouldnt be a good approach for that, right?
)))
Seems quite blocky, I dont think you succeeded in implemententing that algorithm either. Could you share the cirrent code?
At least it looks different so either of them or most likely both has to be incorrect
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Seems alright to me. Maybe you should start debugging the code by first drawing only one triangle, maybe coloring each corner (pixelX0, pixelY0), (pixelX1, pixelY1) and (pixelX2, pixelY2) with lets say blue (after the drawing is done so they doesnt get drawn on top) and compare the corners with the wireframe image to find out whether that triangle even exist there (so the pixel coordinates of the vertices are right). Then you can look whether the drawn triangle matches the corners etc.
When you find what exactly isnt working, you should be able to fix the problem, more easily atleast
How do you usually check for the first time the player does something? For example a unique cinematic that only happens one time. A bool in a Scriptable Object?
@tiny reef you can place tile in run time, but if you need to store data in tile, you need scriptable tile and i am not familiar with this
hm yeah im currently trying out the object pool but ill sea if that makes sense
the thing is i have like 10 and in the future way way more types of tiles
so im not sure how an object pool would work in that case
because every tile is like its own prefab with own script
Could make a singleton and stick it with your game manager, otherwise writing to a SO or some c# script is fine
Nice thanks
for each type of tile you can create a object pool of it and pick it in object pool to avoid massive calls of destroy()
does it matter how many tiles i create in each pool?
because its only once so more shouldnt really matter that much, right?
you can always dynamically adjust your pool, but that requires some extra work
instantiate more objects only when the pool is empty
if you know you're going to use certain amount of prefabs, just cache a few thousand or two
yeah its like a few ten thousand
but that should not be a problem with pools anymore
i mean im planning on doing chunks so there will be a maximum amounts of tiles at any time
yeah i can just instantiate the maximum amount of possible tiles for every pool
And talking about singleton, if I'm making something like a roguelike that the character has upgrades till he dies and he changes levels while playing, is it good if the character has a singleton so in each level is the same till he dies?
If you have a single character, who doesn't say share mechanics with your enemies (can implement around this idea easily), that sounds fine
Not likely to fall into the spagetti problems of singletons that easily, unless you've planning on a large scope of a project.
Well the player is the only thing that has stats rather than health so I think it will be fine then, thanks
if you want to slow down time would using Time.timeScale = 0.5 be the right way to do it? when this happens the whole slow motion just feels like low fps and not smooth slow motion
Window > Layout > Default
If that doesnt help then restart unity
i am very very dumb
it was on something that i have never seen i am very very sorry
Always easier to split logic between the enemy and player anyway, but when it comes to data, you'd most likely want to keep that reusable between everyone, such that you don't hardcode your health decremental method to that of your player reference ;)
Hello everyone, I ran into a problem with AR zoom on android. I made a couple of scripts, but they don't work on android, however, everything is stable when testing the scene. Can you help me with writing the AR zoom script
However, if you have working scripts in the stack, I will be very grateful if you share them
ok im going crazy with this.
I have this code
bool hasHit = Physics.Linecast(startSlicePoint.position, endSlicePoint.position, out RaycastHit hit, sliceableLayer);
if(weaponSpeed >= 200)
{
if(hasHit)
{
GameObject target = hit.transform.gameObject;
It is supposed to make "target" variable into the gameobject that has the scliceableLayer, and that worked till yesterday when I went to sleep, but now I open the project again and now what it does is to make "target" into the parent of the gameobject it hits with the raycast
Use hit.collider instead of hit.transform
And then do yourself a favor and read the docs for those things:
https://docs.unity3d.com/ScriptReference/RaycastHit.html
okey, thank you a lot, but im still wondering why it worked last night and now didnt
havent touched anything, just opened the project to see a thing
added transparency for clarity, but still it does not take into account a large number of pixels for some reason https://pastebin.com/PpBGXQFF
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
This is very simple to do with the GPU. You're already doing half the work in your DuplicateTexture method: creating a RenderTexture, blitting to it, and reading it back into a Texture2D.
You just need to replace the Graphics.Blit with a Graphics.DrawMeshNow with the mesh of the sprite.
How? I've been trying for 2 days now and can't get it right
You added a Rigidbody to the parent or rearranged the hierarchy
Or are just misremembering
I want to copy the texture completely, but only with the part that is displayed on the mesh. The size should be the same and the quality is the same. It seems to me that the render camera and render texture will not work for this. DuplicateTexture I made it only so that you can read and write to the texture
hey, how do I get the terrain reference from a prefab? I'm trying to raycast from the cursor onto the terrain plane in order to get the cursor position on the terrain
What does the prefab have to do with it
my background looks fine in the editor, but in the running game some parts of it becomes like that (the first image)
im sure its got to do something with the code i made for the background to move so posting this here, can anyone help?
I can tell you it definitely works. You don't need a camera to draw a mesh to a texture. Take a look in GL and Graphics. You need to set an active render texture, assign a camera projection, and draw the mesh.
You have not shared the code that you think may be the problem
and the quality and size of the texture will be fully preserved? and displaying the alpha channel?
yeah i like to wait first before posting the code to see if anyone is willing to take a look at it
the size of the texture and its scale will completely depend on the camera and its dimensions and position
Is it a cloud texture in the background?
public class ScrollingBackground : MonoBehaviour
{
public float Speed;
private float offset;
private Material mat;
private void Start()
{
mat = GetComponent<Renderer>().material;
}
void Update()
{
offset += (Time.deltaTime * Speed) / 10;
mat.SetTextureOffset("_MainTex", new Vector2(offset, 0));
}
}```
i think that fixed it, thank you a lot
Hi, in a situation where we have 2 scenes loaded, is it possible de parent an object from the scene 1 to an object in the scene 2 ?
Like this?
I get only transparent texture
What happens when you try?
nothing
no error, no parenting
You might need to first move it over.
You need to set the active render texture before you draw
where to install?
I will try, but it seams not feating well in my project structure (I can totally edit if it's the only way)
In this situation, it's a moving platform and my player, I can't change my player scene, so I need to move the platform in the player scene but it's not a rooted object now (I can tottaly make it root though)
What
like this?
Yes
I imgine that you want the player to follow the platform ? You could translate the player the amount of movement the platform is moving.
I don’t understand a little, but how will DrawMeshNow draw an image on RenderTexture?
Check the parent directly after assigning it
oh, you right XD, haven't thought !
still transparent
Because it's the render target
There are a lot of things that could be going wrong. The method is sound, tho
this is how i save the texture
oh, I forgot I already had this in my code (I wrote it 2 month ago and never touch it after) but it seams I get the platform by using a raycast beneath the player. Thanks for your help.
But it return none. Raycast only work on object in the same scene ?
Pretty sure you should be able to get the object from an other scene with a raycast. I never did it though.
Raycast does not care about scenes
You could also try to use Physics Scene if it does not work, but I would really be surprise if it does not work.
and how then to take into account the transparent background when rendering to the texture? I want to get the same image quality
what am I doing wrong
[Button]
public void MeshToSpriteV3()
{
Texture2D texture = meshRenderer.material.mainTexture as Texture2D;
Texture2D spriteTexture = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
var duplicateTexture = GetRenderTextureWithMesh(texture);
RenderTexture previous = RenderTexture.active;
RenderTexture.active = duplicateTexture;
Graphics.SetRenderTarget(duplicateTexture);
spriteTexture.ReadPixels(new Rect(0, 0, duplicateTexture.width, duplicateTexture.height), 0, 0);
spriteTexture.Apply();
byte[] spriteData = spriteTexture.EncodeToPNG();
File.WriteAllBytes(savePath, spriteData);
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(duplicateTexture);
}
RenderTexture GetRenderTextureWithMesh(Texture2D source)
{
RenderTexture renderTex = RenderTexture.GetTemporary(
source.width,
source.height,
0,
RenderTextureFormat.Default,
RenderTextureReadWrite.Linear);
// Graphics.Blit(source, renderTex);
RenderTexture previous = RenderTexture.active;
RenderTexture.active = renderTex;
Graphics.SetRenderTarget(renderTex);
Graphics.DrawMeshNow(MeshFilter.mesh, Vector3.zero, Quaternion.identity);
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(renderTex);
return renderTex;
}
so i have a problem.
public class PointController : MonoBehaviour
{
private void OnCollisionEnter(Collision collision)
{
Debug.Log("HII");
}
private void OnCollisionStay(Collision collision)
{
Debug.Log("BRO");
}
}
GameObject objec = Instantiate(gameObject,Vector3.zero, Quaternion.identity);
So i Instantiate 2 objects and they collide but i donot get any of those Debugs??
I have a collider on my prefab so anyreason why=
?
Show the other object
it is like in for loop the 2 objects gets Instantiated
You're missing the part where you set the camera projection. This can be done through GL. The specific matrix you need will depend on the size of the Mesh you're drawing. The the vertices are in pixel-space, as in each vertex's position is the same as the pixel coordinate it would be on the texture, you can use GL.LoadPixelMatrix(). Otherwise, you will have to create an orthographic projection using Matrix4x4.Ortho that matches the size of the mesh.
Then they're missing a rigidbody
oh wait
lol True but why do i need a rigidbody
if i am only working with collisions tho :/
Rigidbody is the thing that collides
please tell me how to do it? I'm sure it's just a couple of lines
As I said, it depends on the size of your mesh. Do you know what it is? As in, what is the min/max position of the vertices. It could be from 0 to 1, or in pixel coordinates, or some other arbitrary range, which all change what camera matrix you need to match the size of it on the texture.
bounds of mesh?
Do you know where this mesh comes from? Did you generate it?
yes, this mesh was obtained by cutting a sprite through an asset from a store. And now I want to save this piece too as a sprite
Cut from an atlas of other sprites, you mean?
no, there is an asset that can slice the sprite into pieces along the line, 2d meshes are created, and I want to save them
And the asset only generates the mesh, while using the original sprite texture?
yes, as seen in the screenshots above. under the hood, it uses a polygon collider and generates a mesh of an image piece by triangulation
and now I want to save the piece as a texture to disk.
Ok, so then I would try a basic orthographic projection. There will probably be some trial and error to find the right size so it matches up, but when it does, it should be a perfect copy of just the mesh part.
That would look like this in your method:
...
Graphics.SetRenderTarget(renderTex);
GL.PushMatrix(); // to save the previously loaded matrix
GL.LoadOrtho(); // load a basic orthographic projection
material.SetPass(0); // load the material to render the mesh with. This should be a basic sprite/unlit material with the right texture assigned.
Graphics.DrawMeshNow(MeshFilter.mesh, Vector3.zero, Quaternion.identity);
GL.PopMatrix(); // restore the previous matrix
...
You were also missing the material.SetPass(0), I thought that was a parameter in DrawMeshNow.
It also wouldn't be a bad idea to call GL.Clear(true, true, Color.clear); after Graphics.SetRenderTarget, in case you get a texture with old data in it.
i can't get my bullet to go forwards anyone out there to help me this is my code
public class Bullet : MonoBehaviour
{
public float speed = 10f;
public int damage = 1;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
rb.velocity = transform.forward * speed;
}
void OnCollisionEnter(Collision collision)
{
// Check if the bullet collides with an object with a health component
Health health = collision.gameObject.GetComponent<Health>();
if (health != null)
{
// Deal damage to the object
health.TakeDamage(damage);
}
// Destroy the bullet upon collision with any object
Destroy(gameObject);
}
}
Do you spawn the bullet in the appropriate direction ?
Also, arent they just destroyed on spawn ?
it just does not move forwards
It does not move at all no ?
Probably because they are destroyed on spawn
well no
i had kemetic on
and it stays there
but touched is destroed
destroyed
I mean, in your video they disappear.
THen, start by fixing that.
Ok so then I would try a basic
but the wont move if it wasn't the case
i have try alot of things man chatgbt can't even help me
What you are saying make no sense.
You cannot move an object that is destroyed.
so yea idk what to do
anyone that can help me with this ur a legend :))
is it possible to bake a navmesh on runtime??
In this recorded live training session we show how to work with Unity’s Navigation tools at runtime. We will explore the publicly available Components for Runtime NavMesh Building and look at how we can use the provided components to create characters which can navigate dynamic environments and walk on arbitrarily rotated surfaces, including ene...
Did you do the steps I provided?
Finding the issue is always the first step on solving it
Which is better ?
is it possible to Task.Run a function (I can change the return) that I need parameters for
because its causing random lag spikes, which it wasn't doing before, which is wierd
so I thought I could run it asynchronously to avoid slowing the game
how do I trigger domain reload through code?
Maybe AssetDatabase.Refresh ?
does it trigger domain reload? I didn't see any pop up about it
Domain reload is whenever script are being invalidate ? Which happens if you recompile ?
I can be wrong though.
well I have no idea. I'm just curious
Why would you want to reload the domain ?
there's 0 info online on domain reload besides brief explanation of what it is and how to disable it
because I've no idea what else to try. I delete a directory through editor script and I get errors because Unity doesn't know I deleted something
Ah, you absolutly need to do AssetDatabase.Refresh in this case
but it doesn't help at all
still same errors