#💻┃code-beginner
1 messages · Page 549 of 1
how can i fix these errors? using a sub class here
Need more info ofc.
Is it your own code/code that you can modify?
And show the code that those errors refer to @stuck palm
i can modify the code. when i double click they dont link back to a point in code
its just this repeating for a bunch of other field names
So you are using an asset for outlines?
Seems like that's where it's coming from
Or did you inherit from a class related to outlines
Im inheriting a class from this asset to do some slightly different things
Did you add outlineWidth to the inherited class?
no, the inherited class has no fields
it did when i took that screenshot, but when i took it out, the issue still persists
code still works as expected, though
What asset/package is this?
Quick Outline
The error suggests that they are doing something like cs class OutlineBase { [SerializeField] float xyz; } class Outline : OutlineBase { [SerializeField] float xyz; }
Can you edit the source code?
Or view it
Outline, in my case, is the OutlineBase in your example
yeah
It all suggests that StylisedOutline has some duplicate field declarations. But if thats not the case then idk.
Could try recreating the StylisedOutline components and see if the message goes away
Or any parent class
But that could be a pain if you have a lot of them
interesting, though..
Apparently the inheritance is just MonoBehaviour -> Outline -> StylisedOutline
So I'm stumped
the base class uses properties, could that be something?
the errors dont seem to be happening anymore for some re ason
Not sure when those particulat errors appear, it feels a bit inconsistent
I have a script that automatically loops my background graphic when it's autoscrolling by shuffling a copy back to the right of the camera once it leaves the visible area to the left, but over time the two graphics start becoming misaligned... I tried solving this by moving the code from Update() using Time.deltaTime into FixedUpdate() and it mitigated it somewhat but there's still ugly seams visible every now and then and Im unsure how to guarantee the graphics will always stay at the same exact distance from one another. any ideas?
its happened again after upgrading then clearing my library folder (the only thing that could possibly be causing it is debugging in rider?, ive tried closing it though and it still wont reload properly)
update:
looks like its just the package manager not responding (in task manager)?
-# 6000.0.31f1
In this case it would be better to sample Time.time directly, instead of accumulating Time.deltaTime over time
If that's the issue here even
Though you should show your code
{
backgrounds[i].transform.Translate(Vector2.left * (ScrollSpeed * Time.deltaTime));
if (backgrounds[i].transform.position.x <= -1 * width)
{
backgrounds[i].transform.position = new Vector2(19 * (backgrounds.Count - 1), 0);
}
}```
reverted back to Update() over FixedUpdate() while testing possible solutions
One thing you can do is to use the Profiler in Edit Mode and see what is taking so long.
Also try an empty scene
how would i do that?
well there's your problem
let's imagine that it resets the position when X < 0
oh I already noticed a mistake I made in there anyways
the problem is that, no matter how far you got past 0, the resulting position is always the same
Consider adding to the X position instead of just setting it
if (whatever.x < 0) {
whatever += Vector3.right * 20;
}
This is a common error in code that accumulates a value over time
it's like doing this
delay -= Time.deltaTime;
if (delay <= 0) {
delay = interval;
// do something
}
It should be delay += interval; instead
and, even more accurately
while (delay <= 0) {
delay += interval;
// do something
}
in case the interval is so small that things need to happen many times per frame
Perhaps I misunderstand, but if you know the width of the backgrounds- why not adjust the position of the rightmost BG, leftward by the width of the other BG(s)?
!bug
🪲 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
seems to work fine now but Ill keep an eye on it, ty
Is there alternatives for drag in rigidbody3d?
Assuming you're working with Unity 6 right? I don't know if Unity2D has this but drag was renamed to lineardrag or something like that
If you search up lineardrag intellisense will know what you're trying to write
Yeah it's lineardrag
Oh ok thx 👌
It's called "linear damping" now
I was wrong rip
Yeah
Seems like an awfully unhelpful name change. I would understand linear drag
It's more accurate -- air drag is proportional to the square of your speed, but I'm pretty sure Unity's "drag" is proportional to your speed
Ah ok that makes sense
i think i have replicated the issue by using the script in the scene, making a change while debugging in rider?
never used that IDE, but generally, if you need to recompile- you need to first stop the debug session.
stopping the debug session and closing rider didnt fix it when it was frozen
ill try see if i can trigger it while not debugging
Rider performance is a bit sluggish for me, I wonder if it can even handle a debugger
I get infinite domain reloads in 2022 I just kill unity and re open 😦
i cant remember how often it happens or whats happening when it happens because it feels random
indeed, the code will continue to run in unity, even if your not debugging it and have closed your IDE.
Burst compiler has this problem update it if you can
Oh yeah - I used to have lots of issues caused by burst
this?
Crashes too
is there a way to disable it if its buggy then?
remove it's package
ugh, thats the worst! alas, you NEED to figure that stuff out to fix it 😦
the button is grayed out
It's depended on soo they cannot
i know 😭 unity 2019 never had these issues
just now saw that
alteast i think it didnt?
I reported this as a bug months ago they never responded to me 😭
agree with this suggestion- even if just to test it out
Sometimes I just copy stuff into a new project for testing, to eliminate all the OTHER junk in my main.
oh hey guys im gonna try this
They claim it's fixed but I don't think it was
What unity version are you running btw
6000.0.31f
Oh oops its right there in the screenshot
yea lol
it didnt fix it :(
i swear its when i try to playtest + debug + i did a script change
Did you ever use the profiler to check what is happening?
i dont know how
also i gotta go but please tell me for when i come back 🙏
You open it from Window > Analysis > Profiler
Then make sure you are profiling Edit Mode and hit record:
Then you recompile
Wont it freeze with unity though?
It should still be collecting info in the background
^Or whatever it was that triggers the domain reload freeze
well, if unity never comes back to life, then you're hosed
Does it redraw or will i have to read a log file?
Osmal, thanks for before I solved my isssue. You probobly do not remember but thanks.
Also another question
Not sure if it writes to a log file automatically or not
Does unity ever recover from the reloading domain state?
Like is it completely lost or does it just take long
I want players to enter a username upon player sprite death. Currently after death the main menu is shown, where users can quit or play again. However, Is it easier to create a new scene (containing an text input element) that displays before the main scene or to modify the main scene to display an input element after player died? Or is there another sollution I have not thought of...
May be a rider specific thing
Damn that looks useful
My longest reload was like 22mins iirc
Will probably take even longer with profiler enabled
Check rob's link though, seems like it would give good info here.
I'm always willing to blame the Version Control package
No fucking way i have to try this tysm
Yea I need to try this too
Hello, newbie in coding here. Can someone give me a tip about what to do in situation with null ? I tried to google it, but i dont really understand it. From my understanding null is lack of .. data? I have a script , but i dont understand how would it be a null, i followed every step in tutorial.
https://www.youtube.com/watch?v=SMWxCpLvrcc&ab_channel=Unity this is the tutorial i have been following for that
The AI navigation system in Unity allows non-player characters (NPCs) to move intelligently through a game environment by calculating and following optimal paths and avoiding obstacles.
In this video, you’ll learn how to get started by setting up a NavMesh surface and how to set up the AI Navigation system package in Unity 6.
More resources:
...
Perhaps that class is using GetComponent (instead of having you assign references in the inspector)
Can you show us the script?
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I'd wager that they aren't assigning anything at all, even with getcomponent. a null object from GetComponent should throw a different exception (which is precisely why it allocates in the editor when nothing is found)
@swift crag
(in the future, please use a paste site -- we don't get line numbers in Discord desktop, and it doesn't work well at all on mobile)
called it. animator is never assigned
okay, notice how this script uses GetComponent<NavMeshAgent>() to find an agent
but it doesn't do that for the Animator
forgor
that didnt fix it FUCK
@swift crag oh it was that, indeed lol. Thank you.
Or did you make this script
Hey quick question, what code do I use to get an image inside a script?
I have a script called "CardDisplay", and I want to get an image called cardSprites in it. But when I do this in the script I want to have access that image:
cardSprites = GameObject.Find("Cards/CardDisplay").GetComponent<Image>();
It won't get the image because of "Object reference not set to an instance of an object." Any ideas?
@verbal dome are u asking me ?
Yeah
did you check the editor logs already? https://docs.unity3d.com/6000.0/Documentation/Manual/log-files.html
im about to profile the editor lke osmal told me to
@verbal dome the script comes from AI navigation package sample . I just simply followed the tutorial
the GameObject.Find call is not finding any object with that name. It is not advised to use Find to get a reference to an object. use a better way: https://unity.huh.how/references
That thread I linked has a unity employee reply how to make it log what threads are making it be stuck
oh ok
https://hastebin.skyra.pw/raw/coxukufigo
heres the logs just after i ended unity (1min domain freeze)
(i didnt ping bc idk if u wanted a ping)
I dont see anything that takes more than ~12 milliseconds there
Wdym ended unity? Did you kill the application while it was frozen in domain reload?
yea because i waited a reasonable(?) amount of time
normally domain reloads take less than 16seconds
for me atleast
I assume that it logs things only after they are completed
So killing it while it is frozen would not let it log the thing that is actually taking long
Just assumptions though.
i enabled that thread thing rob was talking about too
I presume it will log that if the unity person bothered to even post that.
I would let it take as long as it takes and then check the logs
it hangs tho?
Yeah, you generally need to get past the bad part
I guess you could start stabbing at unity with a debugger
For 20 minutes? Worth the wait.
When I get this it never completes it's broken for ever
it never responded
Waiting a minute for a domain reload Is a reasonable time. Make sure you're on the latest version of Unity and investigate to see if perhaps one of your plugins or assets is what's causing the long domain reload. Occasionally it's an editor bug, but a lot of the time it's code hooking into reload callbacks.
delete library folder, refresh
always fixes weird hangs for me
we're trying to figure out if anything useful appears in the logs
tried that
there is an Evil Gremlin
Best I figured out was burst compiler threads were still running when I last looked into it
Just let it do the whole domain reload and check thelogs afterwards.
It doesn't die if you have a compile error, right?
ive disabled burst
I'd add a gratuitous typo and then load into safe mode
it wont ever finish the reload though
actually, that would stop pretty much all asset importing, so that might not be useful
is my unity just cursed sfm style 😭
I'm soo used to it I kill unity if it takes more than like 10s and re open
Standalone profiler could help too.
(You can use that for edit mode, right?)
tried that and it didnt really do anything
ill try again
I guess it won't report anything until it unfreezes
Is it possible to call a method from one scene in anoter scene?
So yeah, problematic
Yeet it
Does anyone have a tutorial for moving 2d instantiated objects forward the direction they're facing?
Given the Transform of the object, you can get transform.right or transform.up
(transform.forward would be into the screen in a 2D game)
This tells you which direction you want to move in
There are many different ways to move objects, so there's nothing that will be useful in general. What Fen said about the directions is correct. Use those with whatever your movement code is.
You actually have two smaller problems here!
- How do I know which way to move?
- How do I move?
The second point will vary. Maybe you have a Rigidbody2D, or maybe you're just pushing transforms around
it just stops updating when unity freezes, even though its the standalone one
also removing probuilder didnt fix it
i think if i am
in play mode + just was debugging a script with breakpoints in rider + make a change to said script THEN
stop playmode (i have only compile after playmode on iirc) -> reload domain freeze
I wonder if attaching a debugger to unity would reveal anything interesting
I was doing that while trying to diagnose editor freezes
(it's very confusing and complicated)
does that happen on an empty project?
can #nullable enable cause issues?
it shouldn't, never seen it cause any issues
Ok, I have been banging my head on this problem for the last few hours, im working on a first person camera, the code is correct but the camera just moves 2 or less degrees and then instantly resets to 0, has anyone else encountered this problem?
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Im confused as to what you want me to do here, its just text...
use https://paste.ofcode.org to share the script you're writing
Nothing in here is setting the rotation of the camera
Theres two scripts
Ye xD
Sneaky
You're directly setting the rotation of the player's transform
This is a problem because the Rigidbody also does that every frame
It's going to clobber whatever changes you tried to make
Consider setting the rigidbody's rotation!
You are using the mouse delta for camera rotation
oh, that too
This will not be added together over time, it's just how much your mouse moved this frame
hmmmm yes yes, very valuable info.
I usually keep track of the camera's X and Y angles in the camera script and add the mouse input to those values
While clamping them
Then I apply that rotation to my camera
yep -- just sum up the changes over time
Well, just clamping the X really
I will try...
ok but where the hell is the rotation of the rigidbody being reset? Or where is the rigidbody resetting the rotation of the camera?
the rotation of the camera is proportional to that frame's mouse input
if you stop moving the mouse, the camera goes to [0,0,0]
because lookX and lookY are zero
that's why you need to add up values over time
You also have a problem with the rigidbody, though. Since Interpolate is on (which you want), it's updating the transform's position and rotation every frame
Whatever changes you make are ignored
You'll need to get the player's rigidbody and set its rotation for the left-and-right rotation
Plus, you want to do camera rotation in Update or LateUpdate instead of FixedUpdate
yeah, it'll look gross otherwise
Otherwise it might not update each frame
Since FixedUpadte isn't necessarily called each frame
I like to force the camera to look in exactly the right direction in LateUpdate (not just setting the up-and-down rotation)
I did add them up, now the Player (aka rigidBody) is rotating but the camera isnt.
Show updated code
ye sry, i updated the links ( the code), idk if I did it correctly 😅
This is not addition:
Wait, I got it to work, only the X is reversed but I can just reverse it back, and rigidbody's movement is not good...
Yeah, there are more issues
You are rotating your player with player.transform.rotation = Quaternion.Euler(0, lookY, 0);
Since the player has a rigidbody this is incorrect, you shouldn't modify a rigidbody's transform directly
Use something like rigidbody.MoveRotation() instead, and enable interpolation on the rigidbody
Although, the camera rotation relying on the rigidbody's rotation is just asking for trouble..
Also you are still rotating the camera in fixedupdate
I updated the code again.
Post new link here, it's easier than going back and forth
What type of game is it btw, first person? 3rd person?
First person
Im just making anything, so I can learn syntax for when I actually start working on a game
Start with rotating the rigidbody correctly instead of using transform
That seemingly changed nothing.
What did you do?
You can post small code snippets with backticks. #💻┃code-beginner message
swapped rigidbody.transform with moveRotation
rigidBody.MoveRotation(Quaternion.Euler(0, cameraY, 0));
I have a scoreTable script called scoreTable in my main Scene. It is attached to an empty gameObject. I want to from my other scene where the game is running on be able to from a script there to call a method from the scoreTable, called AddHighScireEntry. is it possible?
Thanks in advance
Just a heads up , you are setting the Y velocity of the rigidbody to zero always and also consider using lateupdate for smoother camera movement.
Yeah I saw that, that is also messing with its falling speed, its annoying!!!!! Thanks for the tip.
just use rb.linearvelocity.y or rb.velocity.y where the zero should be
Maybe dontdestroyonLoad would work?
Ok so that causes my player to fly away if I turn and walk at the same time.
DontDestroy just puts the gameobject into its own scene called DDOL.
Anything there CAN be accessed from other scenes, but not through the inspector , You can access it with a singleton or clever Dependency Injection
afaik something like FindObjectByType only works in the Active scene
hmm, I will look at that then
is that the best way to do it do you think?
Hey, how do I change the source image to a new sprite from the "Card Image Randomization" Script?
Here's the code from the Randomization Script. Whenever I look at trying to figure out how to change source images, it keeps being weird.
public void Start()
{
AddCardImage();
}
public void AddCardImage()
{
cardSprite = mainCardSprites[Random. Range(0, mainCardSprites.Length)];
}
}
Thanks
Oh hey spawn!
imageComponentReference.~~image ~~sprite = yourimage;
for a sprite renderer its spriteRenderer.sprite = yoursprite;
Image also uses the sprite property
what does "being weird" mean?
Your code selects a random sprite from the list and then puts it into cardSprite. It doesn't do anything eles.
As in the source image isn't changing, but when I look up to see how to fix it, I can't see how. Going to try Spawn's rq...
well, yeah
you aren't doing anything to the Image component
so nothing will happen
you equally should not expect the color to suddenly become red!
That's true 😅 Sorry, Im very new, didn't even know it was going to be image component. Thanks!
what is "UT" in this context?
btw usually hit up #💻┃code-beginner nvm me lol /lostdiscorder
did you forget where you are again?
I believe Im in code beginner, did I mess something up? Apologizes if I did.
Fly away?
nah, i think nav might have just gotten confused
Hey Spawn and Fen, don't know if yall are still in here but wanted to say thanks for the help!
unit testing
the test runner package should already be installed, unless you've gone and uninstalled it yourself. you can read about how to use it here: https://docs.unity3d.com/6000.1/Documentation/Manual/testing-editortestsrunner.html
you right.. it is sprite for either or.. idk why i was thinking .image
also.. is this that "intellicode" i keep hearing about? lol..
first time using
in ages. i disabled Co-Pilot but had forgotten about intellicode..
need a random unit test for "da grade" and am assuming unity made it more convoluted than "just doing a unit test in cshart"
i was like "daaaang.. studio has gotten smarter since last i used it" 😅
oh
found it
yeah scrap that question
ok an actual question this time around
how do i access obj instances through a test script without making said script execute every frame
(which i assume [UnityTest] is doing)
you should really read the documentation about the test runner package
ops yea lol
doesnt help much
considering there is an entire course that takes you through exactly how to use the package with excellent examples, exercises to complete (and their solutions) right in the package documentation, i sincerely doubt that it doesn't help much
traitor ! jk
can you juts tell me how do i reference my GameManager from a test
does it exist in the test?
take a guess
no
correct
so if it does not even exist, it isn't a matter of getting a reference to it, you need to instantiate it
crazy how that works, right?
well i cant instantiate it if it doesnt even recognize its type
ah and here we come to the actual problem. you didn't read the documentation about setting up asmdefs for your project.
soo "get bent"
cool
sure, if "go read the actual instructions instead of asking redundant questions that are answered by the instructions" is the same as "get bent" then yes, get bent
your idea of "the instructions don't help because i didn't read them" is not appreciated here
why does this thing have to exist, is this even useful?
Do you know how assembly definition works?
what does what?
lowercase unity struct
i can guess what it does
https://docs.unity3d.com/Packages/com.unity.mathematics@1.3/manual/index.html
provides vector types and math functions that have a shader-like syntax, similar to SIMD or HLSL. The Burst compiler uses Unity Mathematics to compile C#/IL code into highly efficient native code.
that is why it exists
Don't guess, Learn how it works. Assembly definition will help you reference components for your test suite.
i assume its tangentially related to "hey use this stuff"
don't make assumptions. make an effort to learn
yes, that's "Intellicode"
OK
let me guess, you're a reddit outrage tourist?
new profile, checks out
eyyyup
nah they are just playing
"read the documentation" is not toxic.
But you are
spoonfeeding every step would be more "toxic" because they wont learn
when you assume, you make an ass out of u and me 😉
it is how you word it
I would strongly recommend making some friends
They help when it comes to social skills
also no im not forming conclusions on the server as a whole on you alone
if you dont have anything useful to contribuite or help, you should refrain from posting just to stir shitup
can a <@&502884371011731486> clean up this off topic nonsense
assembly definitions determine which assembly each script file is associated with
importantly, they also include a list of assemblies that'll be referenced
if im being told to "read the documentation", not being given a link, and the only one i could find leads to a rabbit hole of jumping through doc pages
yeah i'd call that dick behaviour
right so you decided to specifically say that the documentation was not helpful, then you almost immediately demonstrated that you didn't bother reading it and assumed i was just telling you to get bent.
the toxicity is on your end, mate. but that's okay i don't have to help you
that is how i'm reading this, yes
literally the first thing i did was give a link to the documentation #💻┃code-beginner message
🍿
too busy ragin, less reading
this is non-helpful
wait nvm it is the convoluted shit
tbh personally dont find unit test as useful in games as I do in regular apps
I prefer other kinds of analysis
I wrote some tools to scan for missing serialized references, for example
a bunch of validators!
there are just so many possibles with games its diffcult to unittest
Is there anything wrong with this documentation, @flat sphinx : https://docs.unity3d.com/6000.0/Documentation/Manual/assembly-definition-files.html
they can still be useful in very very large-scope games
they can but there are better ways imo
then I just violently soak-test the game at 30x speed
The answer is that if you're not using assembly definitions across your project you won't be able to reference that content
probably? but im also not gonna split hairs over slapping a UT for "hey are you implementing all of these fields correctly" if polite asking is all your lang gives you
If a script does not have an assembly definition, it gets thrown into Assembly-CSharp, which you can't reference explicitly
or texture validification or such
which is a problem, because the Unity Test Framework looks for tests in code that's explicitly put into an assembly
You can, however, just throw everything into a new assembly definition. That's roughly how my game is set up right now.
Everything in the scripts folder is in the "GameName" assembly by default
Except you'll need to handle Editor folders
I punted the editor folder out of the scripts folder 😛
thank you
A folder named "Editor" puts its scripts into the Assembly-CSharp-Editor assembly by default.
which references Assembly-CSharp
Generally that's correct. As you can have them everywhere, some projects are more difficult
I'd have done an explicit editor asmdef if I had anything more complex going on
why not create a proper editor asmdef?
any place to peek the defined assemblies?
i haven't had a reason to yet!
Your IDE should have a list of every assembly
But yeah a single root for runtime scripts and one for editor (if any) per logical group is the typical asmdefs setup
You can also search the project window for t:asmdef
yeah, it still has an assembly list
see..."Solution Explorer"?
yeah, there should be a Solution Explorer window
you can focus on it from the command palette if needed
I dunno if Unity has a straight-up list of the assemblies it knows about
Does that actually work? I've always assumed you need an editor asmdef to reference the runtime assembly
assumed theres nothing in the explorer view besides files cuz of how barebones it typically is 
everything is an .asset in unity
everything is auto-referenced by Assembly-CSharp still
(well, I made my giant game assembly auto-referenced, at least)
Oh right that makes sense
so the default editor assembly eventually sees it
Trash, but makes sense lol
I don't think I have anything inside Assembly-CSharp!
nevermind, one random constants file 
(used by a build tool)
none game with left beef
barely use c# this is word salad to me
thats more of a unity thing than c# related
.asset is a generic extension used by many unity assets
I have a ton of localization tables that all use that extension
% find Assets -name '*.asset' | wc -l
2423
kersplat
eee @swift crag like this?
every scriptable object asset will also be an .asset file
That's the default assembly that Unity throws everything into, yeah
in file explorer only thing that doesnt are raw files like .cs or .png etc.
You don't manually edit the assemblies, you need to use the assembly definitions in Unity
just having a peek, I imagine
ama restart vsc or sm then cuz intellisense still refuses to gimme the class
But yeah you can see that the default assembly will reference everything, but references can't be two way so there's no way for the test assembly to reference it
If you want to run tests on your game's code, you'll need to throw all of your game's script assets into a new assembly (an asmdef in the "Scripts" folder will do). This will cause a giant pile of errors.
You then need to explicitly reference each assembly your code depends on. It should be pretty intuitive based on the names of the assemblies and the errors you're getting
You can then reference your game assembly from the test assembly
mmm, assemblies!
the .asmdef files created through "create: tests assembly folder"?
Hey so i got a question... I'm wanting to learn coding so i don't have to rely on outside sources, but where can I go to do so?
if so then yes thats what im doing
I presume you're following https://docs.unity3d.com/Packages/com.unity.test-framework@1.4/manual/workflow-create-test-assembly.html ?
nah im just pressing buttons that look like they lead me to workingening 
consider following the tutorial, then
graaargghghh fiiiiine
https://docs.unity3d.com/6000.0/Documentation/Manual/assembly-definitions-creating.html
Creating an Assembly Definition asset
You will need to do this to encapsulate your own runtime scripts so the test assembly can reference your scripts via this asset
er, vice-versa
the test assembly references the game assembly
that somehow just made it workse
vsc wont pick up intellisense in the test folder anymore
I would kill VSCode, regenerate project files (Preferences -> External Tools), then reopen VSCode
I'm pretty sure I had to do that after creating a new assembly
fun
I also had a really funny issue once where all of my .csproj files had everything in them twice for
some reason
even when regenerating project files! it was very weird
I just nuked all of the .csproj files to fix that
well it works now
now i can actually write the test
yippie!
ok so how do i tell if a class' member is actually set and not the weird voodoo not-set that unity seems to populate non-nullable GameObject vars with
field w/e
field != null will do it
== and != are overriden by Unity so they check for the "fake null" state of Unity objects
👌
As a complement, avoid using x is null, ?., ??, ??= on Unity types (the ones deriving from UnityEngine.Object) - these bypass the fake null check and you can get exceptions with these, as the object will be destroyed but not null yet
noted
probably wont be using most of these anyways
besides ?., im a big fan
buzzkill
?. only works on c# objects System.Object
like Action
etc
coroutines you can use ?? since they are regular Coroutine(YieldInstruction object) / IEnumerator methods
Debug.Log(myVariable is not UnityEngine.Object): with this you can know whether you can use the null-operators on the type. If you get "True", all good, else avoid
h m
h m
h m
so how do i wait until Start() has executed
yield return null before stuff?
nop that didnt work
prolly breaks cuz its not initing it in the first place but then uhhhhghghhghg how do i init it proper
cuz the Initialize() whatever it was called i don t think includes editor mods
If you can't provide a dependency, you'd usually use a dummy object.
Or refactor your code such that it works well without that dependency.
Which might make the test useless. Honestly, I wouldn't get into automated tests as a beginner.
Anyone know how to go about using inheritance for mineable/harvestable resource nodes for a survival game? Should i have a base class called resources and then a derived class for stone/gold/iron/wood/logs? Or should i sort it even more by having a base resources class then stone and wood each deriving from it and then from stone have iron/gold deriving from stone and then from wood have logs or different tree types deriving from wood?
Isn’t resource nodes a godot thing?
oh i just mean like resource nodes as in mineable objects in a survival game
they're trying to abstract their game objects
Oh wait nevermind.
how much do you plan on doing each resource? do they need to be classes? some stuff can just be a simple enum or SO
It depends in behaviour that you expect each to do.
i think you need to start at the beginning
i.e. gameobjects + components
Resource : ScriptableObject Wood : Resource
etc.
If each kind of resource "behaves" the same way, there is no need to have a class for each resource
just create a scriptable object asset for each one and reference that whenever you need to identify a resource type
true
You can attach things like the name and the graphics to that asset
To me, a "resource" is just an identifier
You staple a name, description, sprite, etc. to the identifier
hmmm not exactly sure yet. Just wanna have like stone/iron/gold/wood atm and have them be able to be mined with a specific tool so stone can be mined with a low lvl pickaxe and wood with a low level axe. Then iron/gold will require higher tier tools. Also having each resource have a different set amount of items it can drop, the resource name, description.
This could be a property of the "resource nodes" rather than the resource itself
but if it is a property of the resource, then you can just add more fields to Resource
like recipes?
so much easier with SOs
Also having each resource have a different set amount of items it can drop, the resource name, description.
so hang on a second...
You're describing a thing you can go and break to receive items
Yea
different kinds of stones/ores/trees and stuff
I see. I misunderstood your original question
I was thinking about the things you get from mining, not the things you mine
ooh all good
String name. Int minToolLevel. String description. Enum toolType.
I'd consider putting that data into the "resource node" prefab
You can have a list of valid ways to gather than resource node
maybe "pickaxe with at least 50 power"
You wouldn’t need inheritance. Though if you do later on you can use composition.
Yeah, no inheritance here at all
unless you have complex resource-gathering mechanics
in which case you'd have different classes for different "modes"
like, if you have a deeply complex wood-chopping simulation, then yeah -- you're going to need code for that
But if every node is harvested by smacking it with a tool, then you don't need any special logic
You only need it when the logical operations are changing.
i mean wood might be different than stone as i'd need an axe to mine it or a pickaxe to mine the stone
That's not conceptually different, though
you're just smacking it with a different tool
"different" would be something like requiring a unique minigame to be played
vs. just beating the crap out of the rock
wait so how do i do different resource nodes like that though without having to make an entirely new script from scratch for each one?
You'd have one ResourceNode class that stores a few things
- What you get for breaking the node
- What you need to break the node
notably
The way I see, there's a spectrum.
One end is "unique class for every single thing". This is ridiculous because there's probably a lot of common behavior between different things in your game -- a blue skeleton works a lot like a red skeleton.
One end is "one class for everything". This is ridiculous because this class has to be flexible enough to do absolutely everything, even though it's very unlikely that every "thing" in your game needs to be able to do every possible interaction.
By having each instance of it contain different data
If absolutely everything needs a different class you should use something like bytecode instead.
so i'd just have the ResourceNode script that'll have all the important data and stuff in variables about the nodes stats and some methods on in involving the breaking of it?
and i just use that same script on each gameObject?
Right. You'd have one ResourceNode component.
Now, each prefab could have very different art assets on it
one might just be a rock; another could be a very large crystal with an elaborate animation when it breaks
This is a very important skill: realizing when two things that look different are actually the same concept
what if i wanted the tree to be a bit different from the stone in the future though like only the tree could get burned down by some fire element damage and if it got burned down than it wont drop anything or something like that
put a Flammable component or something that destroys object when consumed by flame
i just want a basic test to be able to say "i donded unit tests give me good grade"
dont care for all the ci fluff surrounding it
also what about inheritance with items like tools armor and just normal items
should i use it with that
like items class
Then yeah. You’d likely need inheritance for something like that.
is annoying that i have to jump through hoops when i just want to check if vars in a list arent null
then armor and weapons or consumables and resources
Perhaps. You can have tools, armour, consumables, etc all derive from the items class.
Does it have to be in unity? And even more so in what seems to be an actual project environment? If it's just a task to make a unit test, maybe write some simple console app and make a unit test for it?
ok
public bool fire_interaction(){
if(!this.has_trait(TRAIT_FLAMMABLE))
return
[...]
}
we need to make a full on game
that part i have down already
just need a test as a last-minute slapon
Don’t use snake case :P
yesnt
Then either investigate why this test fails or write a different one.
i mean its failing cuz im trying to reference a singleton that hasnt been initialized
which would be fine if half of its vars werent slapped on through the editor
as for "write a different one" am failing to think of any that wouldnt be pointless
You need to implement an initializer for the test environment. That's part of writing tests.
always had it handled for me uhghhhhhhhh
ok
so if im to do that im back to the "how do i set a gameobject variable through code"
Hey 🙂
I have a question about how to handle and gameplay-pause and unpause system i'm trying to create. it's simple and it sounds like this:
first event: player levels up.
UpgradeSelectionUIAnimation() <--- waited for the pause to finish.
next event: player selects upgrade.
await GamePauseAnimation(!isPausing) <---- waited for the selection animation to finish before resuming.
this is the system i want to create and i've already create the player levels up bit.. but i made it using Coroutines...
Question:
should i be using async/await Task or continue using coroutines. I think i see an issue with this using coroutines.. but not sure exactly.
any help would be great. thanks
gameObjectVariable = gameObjectReference
cool
how do i sanely get gameObjectReference
In various ways. The ideal one is assigning it in the inspector. The less ideal ones are using the Find methods to find it by name or to tag.
yyyes i cant use the inspector for tests
i mean i can if i assign stuff directly
i think
but here im trying to test game_manager and that itself has its stuff set through inspector
when I press play my character falls through the map and I can still jump no matter where my character is how to fix it
and thats enough layers of editorening for the "working around it" making me ask if im testing the code or the test
you didnt add a collider
sorry incomplete screenshot
you didnt add a collider
to the floor
either that or uncheck is trigger
you would need two colliders if you want it to Collide with solids while still using OnTrigger
wait so ground didn't have rigidbody
Rigidbody is for moving objects
usually
colliders are what create solid ground/walls/objects..
uhh what
Can someone give me a tip how to add this receiver? My "AI script" has target and i filled it with my other character. My animator has transition between Attack and Run. Unity newbie here
Can someone explain me how to dynamically create a GameObject ?
I would like to create this alien from c# and not from here (this will be a wave of mob) ^^
@slender nymph im trying to understand it. I have three components, one is animator , one navmesh system, one AI target script. "Make a method matching the name of the event", what is an event? Is it like a parameter in Animator?
make a prefab, use Instantiate
98% of the time you do not need to create a GameObject at runtime
(thats using the constructor as such. GameObject go = new() )
you have an animation event called PlayStep on your GrenadierWalkFast animation. was that intentional? if not then remove it, otherwise that is the event
Ok thx, where is the button ? Somewhere hidden in right click ?
drag ur alien into the Project view that creates a Prefab, you can delete the one in the scene, then making a script with Field like Transform and put your prefab there, then you can call instantiate method and use that prefab referenced in the parameter
@slender nymph yeah, i was searching for it. But the problem is.. i dont know where to find it : D Can it be in the animator?
it's on your animation
like the guide i linked even gives links to explain what window you need to open
Thank you! I'll read this 🙂
pretty much code channel
explicitly ask for review
h m
then
review my code k plz
specifically the update_aim part
im not convinced the math cnat be done easier
hey guys, im super new to all of this, and I was following along to a tutorial, and in the tutorial, the word Input goes green and the script works, but for some reason it doesnt work for me
configure your !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
well first you should probably post it properly using links
me?
yes you
uhh how do I do that? sorry im very new to all this 😭
pastebin?
that site is shite
any of these in !code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
There is links from the bot that show you how
? y so
thanks
heard there are sus malicous stuff going on, also the layout is fucking horrid, half the realestate space is wasted on "other scripts" and usually its crypto scams
@slender nymph Sorry i know im dumb when it comes to Unity. But i ve searched all these lines and i cant find this PlayStep event anywhere here. Im on the GrenadierWalkFast clip, so its right place. Or am i in the wrong place?
Anyone know how to fix this warning from popping up? Assets\KinematicCharacterController\Examples\Scripts\StressTestManager.cs(41,29): warning CS0618: 'Physics.autoSimulation' is obsolete: 'Physics.autoSimulation has been replaced by Physics.simulationMode'
i tried changing the Physics.autoSimulation to Physics.simulationMode and it didnt work
h m
well anyways
https://hastebin.com/share/niyutilutu.csharp
rebieb plz
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
simulationMode is probably an enum
and did you save after?
@rich adder @slender nymph Thank you. Its indeed that.But i am unable to delete it. I guess its cuz of the clip being in the "read only" mode hmm....
whats your main concern ?
can update_aim be improved
you should be able to in the original Asset of the animation in the Importer settings
oh damm yeah you lost me at "math"
damn 
jk but yeah im bad with trig.. maybe make a thread or post in #archived-code-general . its gona probably get buried here
@rich adder ok thx
btw for setting position rotation , its more efficient to do it once
there is a method, transform.SetPositionAndRotation
wayyy too fucked to take nay advice
You don't really need to do trig if you dont want to
What type of game is this, like what perspective?
well i want to rotate + scale the arrow as i move my mouse so
this snake casing is driving me mad
isnt the default quad orientation upwards
Ok so things move in the X and Z plane
ye
You could replace a lot of that with... cs Vector3 direction = mouse - transform.position; direction.y = 0; transform.forward = direction;
That's all you need to do to rotate
But ofc it does similiar trigonometry under the hood
Ill tell you silly stuff , like cache your Renderer instead GetComponent doing it every frame
oh damn
yyeaaha i probably should
yea i saved after
^Actually you would rotate aim_arrow but yeah
alright so what did you set the enum to? and what was it set to originally ?
the Asset creator never updated for the new API i guess
also those are just Obsolete warnings, they are not game breaking usually
uh the lines just looked like this originally
hmm rotate through that then direction.z += base_offset + scale_magic * magnitude?
that'd probably be better yeah
i tried changing it to Physics.simulationMode like it said and it got the red squiggly lines under it and gave an error when trying to save
any way to retrieve the coords from that to pass onto the shooting code tho?
well, what was the actual error?
you can't just stop at "i saw an error"
Assets\KinematicCharacterController\Examples\Scripts\StressTestManager.cs(41,29): error CS0029: Cannot implicitly convert type 'UnityEngine.SimulationMode' to 'bool'
i told you its an enum now
if you don't use the example stuff you can also just delete it
you've tried to take the logical negation of an enum
which is non-meaningful
it's like asking for "not 3"
idk...6?
smh thats obviously 0
i just looked at that but i dont rlly get that means or how to change it so it works the same way it did as before
Cannot implicitly convert type 'UnityEngine.SimulationMode' to 'bool'
You have an object of type UnityEngine.SimulationMode
You tried to use the ! operator on it
The ! prefix operator only works with a bool
Therefore, C#'s only optino is to try to convert a UnityEngine.SimulationMode into a bool
It's an implicit conversion because you didn't do anything to try to convert it
a lot like writing int x = 1; float y = x;
x implicitly converts from int to float
The compiler finds no way to achieve this, and so you get an error
You cannot do it like before without thought out modification
since you cannot negate a enum like a bool as mentioned
also now you have those 3 modes so you have to know which one you need and more importantly why
An enum type represents a set of options
I have not used KCC recently so not sure
My guess, flopping between FixedUpdate and Script with current option
ok, ya idrk which one is the same as Physics.autoSimulation either
since this has to do with physics, you're just switching betwene fixedupdate and script
how do i select FixedUpdate then Script?
simple if/else statement, or something more fancy with bitshift ig?
ok
disabled = physics.simulationMode == SimulationMode.Script
assuming disabled wants that and not the opposite disabled = physics.simulationMode != SimulationMode.Script
also i got another question about this, should the ResourceNode script be inheriting from Monobehaviour, and did i do this mainly the correct way so i can add it to each unique type of resource https://paste.ofcode.org/hzCbYxY8XtjZ3mRGX6rUDj
if its a component(placed on a gameobject) it needs to inherit MB
why are you declaring enum in there
uh idk someone gave example of what to add for the things i wanted each node to potentially have and they said this:
String name. Int minToolLevel. String description. Enum toolType.
declaring the type as field/prop is different than defining the type
Put it outside the class
It looks like you’re trying to define some data
irrelevant , you still need a field for it
That has sort of ‘default’ values for a type of node
Like an iron node always needs x tool level and drops 10 iron is that correct?
In that case monobehaviours that you attach to objects doesn’t really seem like what you want to be doing
the premise here is to have a single ResourceNode component type
each prefab will have a different configuration of the ResourceNode
yea like i wanna have the resourcenode script as the base class for other objects, so if i make and iron node i can set it to need like tool level 2 has lets say 20 iron total and drops 2 at a time or something and requires a pickaxe and not an axe of tier 2
sorry to interrupt here guys but I've got a quick question about mouse input data.
I get lastMousePosition = Input.mouseScrollDelta; on RMB button down.
I then look for Vector2 mouseMovementDelta = (Vector2)Input.mousePosition - lastMousePosition; Debug.Log(mouseMovementDelta);
the debug log shows that the initial press of RMB each time returns the distance between 0, 0 on my screen and the mouse. So I can leave my mouse still and right click a bunch and my camera (which is supposed to pan, and works great once held) teleports hundreds or thousands of units at a time. what's going on here?
oh
hold on a second I might be stupid
public class ResourceNodes : MonoBehaviour{
public string resourceNodeName;
public string resourceNodeDescription;
public int itemDropCount;
public int maxItems;
public int minToolLevel;
public ToolType toolType;
}
public enum ToolType{
pickaxe,
axe
}```
If you want to be fancy, you could give tools different kinds of "tool powers"
a pickaxe would have lost of "break" power and a little "dig" power
a shovel would have a lot of "dig" power and a little "break" power
Why are you using mouse scroll delta for mouse position 🤔
yep I'm stupid I had mouseScrollDelta as a leftover instead of mousePosition lmao fuck
splat
Not too sure what you want to be happening but mousescrolldelta is the scroll wheel and that doesn’t sound like what you need
classic 🦆 moment
it's always the second you ask for you help that you realize your mistake isn't it
if I hadn't asked I'd have been here for hours!
ooh ok ty
If this data will be consistent between all nodes of a certain type it looks like you’d want to be serialising this data somehow, not storing it in a mono behaviour on every node
that's what prefabs are for 😉
Funny because this was just the conversation in code general
Yeah the issue for me when thinking about how to tackle this problem is it’s then very hard to edit this data on all similar objects at runtime
i think ive seen a game do exactly that
Without really any benefits except ‘it’s slightly easier’ than storing a reference to an so in the prefab instead
yea i dont really know what's right for me lol
i dont wanna get locked into some way and not be able to do something down the line
you wont know until you trail and error
because i did it a certain way to start
it also had.. i dont remember if it was bitflags or just an enum for tool behaviours (f.e wirecutters, hammer, etc)
I would look into scriptable objects and see if that’s what you need
i just know i want the system to be very modular and easily changeable if i need to do anything more with it
having smarts is an iterative process
switching back and forth between "a few prefabs that hold the data" and "a few prefabs that reference the data" is trivial
do the iterations bruv
I don’t think so
bro you dont have to call me out lik etat.... 
If you have 20 different node types with relevant data in monobehaviours on prefabs it’s not completely trivial to have to convert all of those to sos if you then decide to swap
me with 100GB of projects on "hiatus"
I suppose you could write a helper script but
"dw ill get back to it"
I don’t personally see the benefit of using monobehaviours here except saving 5mins of time writing the so class
I don't see the benefit of using a separate scriptable object when each prefab is going to need a unique set of node data
each project is just a more "refined" version of other projects put together and the cycle continues lol
bro my brain hurts from all this XD
if only i had the cares for that lol
how would i do scriptable objects for this script?
Then why are you using different prefabs in the first case
just make it inherit from scriptable object instead of monobehaviour?
because there are different kinds of resource nodes
im just stuck on the same refactor i wanted to do half a year ago 
sometimes its easier to just redo than refactor
it was a redo
well
redo for what i could have redone
everything else is so entangled it needs its own refactor
if it works, refactor only when its absolutely illegible
- You can reference data from other systems without touching the nodes
- You can edit all nodes at the same time during runtime if necessary
- Decoupling and for me personally more elegant and easier to navigate architecture
dont do 5 years of out-of-date kids
it uses unmarked strings for character cosmetics
Cutting classes in half isn't "decoupling"; it's just making more classes
A ResourceNode and a ResourceNodeDefinition would be very tightly coupled together
features["hair"]
and it stores a color
encoded as "FFF"
not even a leading pound
or well SOMETIMES it has it
but you cant tell so you have to pass it into a sanitizer each time
One advantage I can foresee is that changing the definitions will work properly with old saved data
since the individual nodes wouldn't have any of the actual configuration in them
AND SOMETIMES THESE JUST DONT EXIST
SO IF YOU READ YOU JTS GET NULL
I don’t actually think so personally what I would do is give whatever ‘spawning’ system for the nodes the so data and that injects it into the node’s script which is completely generic
When you’re hitting iron ore with ur pick axe you don’t care about the default definition in the so for iron ore
The monobehaviours for your ore don’t need to be coupled to the default data at all
this isn't "default data", though
it's just...data
this kind of ore node drops 30 iron ore
i should try doing some prototype-based cooding in unity
or cshart idk
wanna see how well that paradigm translates over to a non-baby lang
would it be better to just go with inheritance and use a different class for each type of ResourceNode i want so i could have more flexibility in the future, like if i want certain types of nodes to apply special things or do special things to the player, like for example if i eventually wanted to add a ResourceNode called uranium that hurts the player if he gets close to it unless the player has some sort of resistance to the radiation.
composition > inheritance
i dont really get how to do it, cause i could just have the ResourceNode Script how i have it atm with all the important variables and do scriptable objects for each type of ore/tree or something and just change the values for each one
but i dont think that would work because some of them would be different
like uranium wouuld have special effects with it
but then im making a bunch of derived classes that are basically doing the same thing except for like one or two specific types of different nodes that i want
if you want an item that can switch between an axe and a pickaxe, yeah you could do a transforming subtype but that's one hell of an entrance into subtype hell
You'd often have these two concepts work along side one another. Just composition without any inheritance wouldn't get you very far.
its a tradeoff between ease of coding around it and longevity
inheritance is easier than modding in a trait check or even a hook
if you're just doing a one-off, yeah just do a subtype
just know when to bail on it and dont go off the deep end with children of children of children
Again, composition is not the opposite of inheritance. These concepts work together like a charm.
Composition simply means that you split one module into many smaller once. There can(and usually should) be inheritance within these modules.
🤨
i understand composition as how unity does components
or using hooks or traits or such
im so confused XD
Composition is more of has-a relationship rather than an is-a one right?
idk the best way to do it for what im planning to do with different resources around my game that the player can mine/break
honestly just do stuff man
analysis paralysis is aids
i just wanna have different things around my game like different trees different stones different ores and stuff but some ores may have different features than others and same with the trees or other things that my player can mine/break
fr i feel like i've been stuck on this forever trying to decide which way to do it
i feel like im getting so many different opinions lol
as lemons said just do it, don't worry about premature optimizations. Get a prototype made and then you can optimize and refactor later.
yeah you want the bestest possible implementation but you quite literally cannot anticipate every usecase you'll think of
and trying to do so paradoxically just leads to more shitcode
All objects you mention will have the same breaking class, except display differently
and im still relatively a beginner so idrk what's correct for my vision
theres this one dude i know, very epic, knows his shit
holy fuck does he overengineer his code
Start something small and simple. You can always make it fancier later down the road.
he did like parrying/blocking code and it had some 8 return value flags, 7 parameters for entry stuff
overrides for everything
NOTHING used it
out of those 8 flags only some 2 were used
dont be him
just make it work
what about for like a unique ore like uranium that will have a special method for giving damage to the player. Wouldn't that not work if all the objects are scriptable objects from the one ResourceNode class?
youll get there when youll get there
No. You're overengineering again.
I don't even know what your game is about, let alone talk about these tiny details that stopping you from starting.
do you have ore, period, yet?
nope, but ik for sure i want to have ores that do unique things in the future
do you have regular blocks?
but also have similar features to them still
wdym?
i assume you want some minecraft/terraria-esque mining whatever
didnt read into the convo much
Yeah same concept with the survival aspect but not blocky, more like a open world terrain maybe procedurally generated in the future but ill worry about that later lol
and those ores/tree types will be scattered around the map and mineable
what do you have so far
each dropping their respective item drop that will fall out onto the floor as a type of rigidbody that i can than pickup
just the player movement and a flat landscape
starting with SOs sounds like a good plan, especially, if the ore are just values (data). uranium would be a MB script with a reference to the ore SO and a separate MB script that damages the player
this is where composition helps. you can easily add a script that damages the player, or anything within a radius that does not have protection against it . . .
XD thx for the help so far though, i apprecate it
👌
but yeah, just starting scripting out the ores now. make a SO class, create a few different ore assets, then work on unique traits that different ores will have . . .
Scriptable Object are used like prefabs - They spawn into your world with specific information attached to them. Once they are spawn, they should have information to describe what the object is about.
Looking at your pastebin earlier in the chat - https://paste.ofcode.org/hzCbYxY8XtjZ3mRGX6rUDj
This is too simple, ambiguous, and confusing. You're limiting the players to only have two enums, when there could be plenty of other tools type. If you want an ore to break easily with certain tools, then I would suggest looking into bitflags to help identify which tooltype best to work with.
The name and description can be used in a separate class, but not resource node. You can make a class as Item which holds the string name, description, and other things that describe the object in general. Even include rarity, weight, power, etc.
If you want your system to be modular, then start by keeping it simple. Try to use interface to help create composition for unique class and structure to make objects more interesting and complex.
E.g. a Ore class would require a item class, but compose of IBreakable + IBlockable + ICollectable + IPlaceable
Then in your So, you can describe that in your terrain generation process, that orb must spawn around moutain/rocky area of your map. That's entirely up to you in terms of how you play with data in a procedural generation process.
imho, start something small. Try generating the terrain and see what data you need to create/customize. That data that you play with can be saved into SO.
Hello, I have very simple problem. My TextMeshProUGUI property is null.
using TMPro;
using UnityEngine;
public class DebugInfo : MonoBehaviour
{
private TextMeshProUGUI text;
void Start()
{
Debug.Log(text); // null
}
}
I have script assigned to the tmp component
Thanks for help 😉
it's private. if you want it to appear in the inspector it needs to be marked with the SerializeField attribute or be made public (first option is typically better)
I made it [SerializeField] public TextMeshProUGUI text; and it's still null 😦
I think you're missing [SerializeField] tag
Go back to your editor, and you should see a new field in the component. You need to supply it.
Hey everybody, new to Unity but have been programming for years.
Looking for a point in the right direction and topics to research.
I am trying to make a rougelike system where cards can interact with each other.
Example: Using one card makes the next one cheaper, changes the way the next card fires, which element it applies etc.
So far, I've found people suggesting Serialized Objects.
Is that what I should be focusing research on, or do you guys have any other suggestions?
public fields don't need to be [SerializedField] because public are already serialized. Thats just for private
if its not showing up, you likely have compile errors
I'm still struggling to figure out how to handle crop stages for my farming game. I've made an empty GameObject, and drug the FBXs for each of my crop stages under it. On a script on the empty object, I'm trying to write a void plantCrop(string name) method. My idea is that this method would simply find the child with name name + "-seed", and activate it, which would make that model visible. When the day advances, I could deactivate it, find the name-stage1 child, and activate it.
However it looks like the only way to get children is via the transform component? And its indexed, not a search-by-name? Is my idea just not feasible to execute?
Serialize Objects is used to hold prefab instances of your card. I'm not quite sure how unique each card needs to be, but it definitely sounds like it needs to access the game state in general.
Would recommend looking into state machine example to help achieve this process.
This isn’t really an answerable question. You would need to be a bit more specific, otherwise answers will just be random thoughts.
everything
Thank you, noted
You’re basically asking how to architect a game but give barely any info on its design and features
It showed up but after I play the game, it's still null.
I can imagine someone trying to re-create yugioh in this case 🙂
you really shouldn't base your logic on object names in the first place, that will make it super fragile. create some object that stores data about each kind of object and then you can use events to notify your crops/objects/whatever when they need to change their appearance/stage/whatever
What do you mean by supply it?
you need to drag the text object into that slot
See how it says "None (Text Mesh Pro UGUI)"? Please supply the component in that field. (More likely the game object itself in this case...)
I agree with that but I'm struggling to figure out how to "store" the GameObjects/models for each stage.
The only thing I -know- I can do is make a public variable for each stage for each crop, and drag the prefab onto it - but then everything is hardcoded and very inflexible
@white yew @ripe shard
This is Rounds, by Landfall.
My game is taking inspiration from it.
Currently, the gun object the player has initializes the bullet prefab with values such as Dispersion, Bullet Speed, Size, Damage, etc
This has been easy to make, as it is simply changing values.
But how would I go about changing behaviors, for example, how the damage is applied (DoT instead of instant), how the bullet moves instead of using physics (maybe it tracks the mouse, etc)
Prefab/ Scriptable Objects to the rescue!
ok I got it but ngl this is the stupidest thing I've ever seen in any IDE so far
I'm used to do such things in the code.
maybe I can "supply it" in c# somehow so I don't need to care about unity GUI too much? if this is possible please tell me
there are many ways you can accomplish this. one way is you could make a scriptable object that will represent the data for the plants that stores each stage, how long it takes to get to that stage, whatever other data you need. then your seed objects just need to reference the scriptable object to pass it to the actual plant when it is planted, then at each "update" (this would be when your events fire) the plant will check the scriptable object to see what stage it should be at.
of course you can find plenty of tutorials for things like this if you want to explore other options
One best use of this would be the tag system in DOTS. Now granted, this is a little bit more advance subject, but the principle is there. When you activate the card, you can apply tags to specific target your card instructs to. That target will have either a tag for DOTS to process unique behaviour for your entity, or new components added to your game objects. That component/tag defines new behaviour in your game.
I've found 2D tutorials, but there its as simple as swapping sprites. In 3D there are more things to swap, so it seems like I should work with prefabs instead. I get using Scriptable Objects for all the things in your message, but I'm failing to figure out how to "select" the model I want to display based on the active crop type/stage... that's where everything falls apart for me
it's really the same concept. and you can absolutely use prefabs for that, just instantiate the correct stage and destroy the old stage when it updates
or even just have each stage all as part of the same prefab and disable/enable the relevant stages
Have you look into .GetComponent<T>? - https://docs.unity3d.com/6000.0/Documentation/ScriptReference/GameObject.GetComponent.html
you should go through the pathways on the unity !learn site to properly learn how to use the editor and the engine. the essentials and junior programmer pathways will teach you things like how to do that as well as many of the other common workflows
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
yes but I'm not touching it because I'm PHP developer and this is exactly what I want to avoid
maybe it's good in a game dev to just get something out of nowhere inside a class
wtf are you going on about? how does any of that make any sense in regards to the advice to use GetComponent?
I'm used to to DI and instantiate everything or use IoC to have dependencies in my class constructor
well guess what, the inspector is a form of DI. just not some big DI framework
Taking a step back here - Why do you need a debuginfo? Didn't you instantiate the Text UI somewhere in your code? Don't you already have a reference to that object anyway?
it's a bad pattern because I would literally have to get some instance in the middle of a class method
it's almost like there are methods specifically for setting up your object's state at the beginning of its lifetime
This seems to lean towards X/Y problem here.
and that would be the best place to call GetComponent. you will also be using GetComponent (or the superior TryGetComponent) a lot in your code anyway so you may as well get used to it
We've help answered your problem initially, but you're complaining about a problem entirely not related to your initial problem.
ok I guess I will have to use Awake with GetComponent and pretend that it's a autowiring 😄
nah, this is a "i'm a superior web dev so i know everything and the way everyone else does things is wrong" problem
You haven't answered my question - @junior ivy
There are some third party extensions that can add a [GetComponent] or [GetComponentInChildren] attribute that will grab it for you. I do find it a bit odd Unity doesn't have that by now
Oh reading things back it seems like you're just asking about DI, which, Zenject is kinda the go-to for Unity DI but it feels like extra bloat to me to add in-depth DI tools on top of what's already there
because I don't get the question tbh
Why do you need a debuginfo?
of course I need DebugInfo to be able to write a script based on magically injected TextMeshProUGUI property
Didn't you instantiate the Text UI somewhere in your code?
I didn't instantiate anything in my code
Don't you already have a reference to that object anyway?
what reference to what object? I have a reference to TextMeshProUGUI but what is wrong with that?
It does kinda sound like you want to use Unity but you're heavily resisting the workflow. You're gonna have a bad time fighting the current like that :p
To sum things up:
I have to configure my serializable properties because they are not autowired automatically.
just drag them in. unity has no way of knowing what object you want to reference
GetComponent<T> is cached so you CAN just use that, quite effectively
or you can use the RequireComponent attribute and call GetComponent in Reset which is called automatically when the component is added in the editor
I thought unity has some default behavior for that so my bad
Oh really? Reset is superior to OnValidate then for messing with dropped-in serialized Objects?
note that it is only called when this component is added to an object in the editor or when the component is explicitly reset in the editor
Reset is not called in any other context (including when adding components at runtime)
i do all my component checks and assignments in Reset and call that in Awake . . .
I think the conversation mostly revolves around the fact that it's a bit extra that we have to do some of that tho :p
there COULD be better defaults for getting references to things, it's not like it's not an important function haha
it's also super trivial to write some code generator that adds all this for you (and thereby implementing your own GetComponent attribute or whatever)
My question was clear and simple.
Nothing in unity is magically injected. You either reference it in a class structure that can be access by other class or don't. If you are not instantiating the text element, then how are you spawning the gameobject? You should be able to instantiate a class that holds all of those information available for you to use without having to use GetComponent<T>. If you already have a reference to TextMeshProUGUI then having DebugInfo seems unnecessary as you already have that component to play with?
I think it's a stretch to call that "super trivial"
FWIW, stop thinking C# like it's PHP.
it's really not, i could throw one together in just a few minutes if i were really so inclined. of course that wouldn't be as extensible as some of the ones that already exist, but it's super easy to do
but regardless, it's also trivial to do it by hand. That doesn't mean it's not a frequent-enough that it's reasonable to expect some default behaviour around it
easy and trivial are different though
Writing a code generator is definitely not trivial if you want it to handle all cases properly (partial types, name resolution conflicts, etc)
like, it's easy to have my own string class, right? just use char[] or List<char>
but I wouldn't call it trivial
why should I have to do that for the basics
both refer to something being little effort. that was the context i was using the term in. it's the same thing.


