#💻┃code-beginner
1 messages · Page 317 of 1
The error is now underlined
Okay, it's underlined, that's what was missing in the last one
not configured
Good, with Solution Explorer again
how do I call a static member without an instance?
So look at that line and see what's wrong with it. Hint: You cannot assign a value to the word float
it says assembly csharp not compatible
looks like positions is null
You need to assign it first.
The syntax is fine.
Like that
Right-click where it says that and select "Reload with dependencies". That should be fixed
so its confused cause im trying to give a name to a float?
Works, thanks a bunch!
no it's confused because float = lerpSpeed is nonsense
You cannot have a variable named float. So setting it to whatever lerpSpeed is isn't going to work
ahh ok i think i see, sorry im tottaly in the deep end here
you're in the shallow end
i mean yeah obvs but for my c# knowledge i have no clue haha
got it fixed thanks all, seems very simple now ive got it
"identifier expected", basically it expected to see a (variable) name, but it found a = instead. That's how parsers work, they scan your input element by element and yells at you when it's not what they want
ahhhh ok cheers
sup y'all. Anybody know why when I start to write void Update or void Start. And push tab, visual studio auitomatically type for this useless thing:
how would i make something wait for like 3 seconds before doing the next thing "yield return new WaitForSeconds(3);" gives me an error
MP4 embeds into discord. MKV doesn't
Use a coroutine
yield return new WaitForSeconds(3); is only valid inside a coroutine
u can't open mkv ?
Make sure the method you put this in has a return type of IEnumerator. Sometimes people put the similar but invalid IEnumerable by mistake
I can't download them on my work laptop
ok thanks
u know i need converter or enough just tap .mp4 instead?
I'm not going to download a random file off of some guy on Discord
Your screen recorder might be able to export as MP4 if you change the settings
sup y'all. Anybody know why when I start to write void Update or void Start. And push tab, visual studio auitomatically type for this useless thing:
wdym useless thing
That is normal, it's a code snippet Unity adds to VS. Instead of having to type all the symbols manually, it does it all for you.
it's normal
What's the problem?
That looks completely functional
What are you expecting it to do?
yep, but when u create a script firstly, there is only void without private
okaay, and?
when i delete start and decide to write it again, it write me with private
If no access modifier is specified, private is implied
but why do you delete it and write it again?
So? What's the problem?
exactly. Where can I find autofill setting in Unity?
huh
You can also adjust the settings so it doesnt explicitly write private. Google should tell you where
This isnt a unity thing. It's a VS thing
But it really doesn't matter, and being explicit is almost always better than implicit
If anything the Unity template should be changed to add the private
but u know, it doesn't matter for code work, but for my eyes when I have everywhere Start and Update method without private, and here VS tab for me with private it's a little bit annoying
You can modify the default "new script" template yourself to add these access modifiers, if you want
u know where i can do it in VS?
can't find
It's not in VS, it's from Unity directly
4:19
u got ocd or something
4:20
Huh?
We are talking about different settings.
Modifying code style preferences -> From VS
Modifying Unity's default template file -> From Unity
I'm talking about default modifier
If you need to remove the default modifier on code completion, then this is done via the code style preferences in VS.
If you need to add the default modifiers to the auto-generated Unity script, then this is done via modifying the script template located in the editor's program files (https://blog.theknightsofunity.com/customize-unity-script-templates/)
Sorry, not sure what channel this problem fits under, so please redirect me if this is the incorrect channel
I have an orthographic camera that looks at my minimap, a world space canvas group. And the camera feeds its frames to a render texture which is then fed into a raw image in my screen space canvas group. And just 5 seconds ago, it was working. But as you can see, it just stopped updating the texture. What could be the reason for this? Because in my code, nowhere does it make the camera stop feeding its frames. I don't even know if that's possible
You seem to have the "Stop" button (top-center of the window) enabled, can that interfere with rendering?
It's not enabled. Only the "play" button is enabled. It was never paused, it just stopped updating the frames of the camera and I can't figure out why
But yes, if I did pause it, that would interfere with rendering
Ask in #💻┃unity-talk, that's more of a general question
Alright, thanks
what kind of stuff do you put in lateupdate?
stuff that makes sense to run (after update).. like when things settle down a camera tracking script for example, maybe
If you need anything that relies on everything else having moved already, that's a use case. Its typically used for camera stuff
awesome
character animations (updating based on final state of movement/actions)
physics related operations (if u need to calculate stuff based on a final state)
input handling (processing and responding to input after all updates have been processed)
ive only ever written 1 or 2 scripts in lateupdate myself tho.. my code isn't structured that well lolio
All input happens before update, according to the execution order on the docs
How would one have the raycasts pivot while rotating similar to how the model does. I have a class that sets up some rays for firing and there are two sets in this example video.
public class Antenna
{
public Transform agentPos;
public Vector3 offset;
public Ray leftRay;
public Ray rightRay;
public void InitializeRays()
{
leftRay = new Ray(offset + agentPos.position, -agentPos.right);
rightRay = new Ray(offset + agentPos.position, agentPos.right);
}
}
Rays are cheap, there's no need to cache them. You can absolutely just make them on the fly whenever you need them
Maybe make a function (or property) that generates the left and right rays when you actually intend to use them
I'm doing it that way mostly because of how I want it set up in the inspector
Ray being a struct it may be actually more performant to not have them as fields, but as locals instead?
You can still have all the properties set up in the inspector, just generate the rays when you need them instead of only whenever InitializeRays is called
true but I'm less worried about performance atm, I can always optimize later. Right now I just want the rays to pivot their positions long with rotation of the cube model
So, generate them when you need them instead of doing it once and never changing them
Your code already uses agentPos's orientation. You're just only checking it in InitializeRays
Yeah in that case you must create them each time because the values you pass to it are computed once, they're not reactive
I guess I'm just not understanding what I'd need to change.
Meaning if the position/rotation changes and you get the ray again (if it's a field), then there will still be the old position/rotation in them
Get rid of leftRay and rightRay, and InitializeRays. Whenever you need a ray, make one on the spot.
so instead of:
antenna[i].InitializeRays();
if (Physics.Raycast(antenna[i].leftRay, out RaycastHit hitL, .75f, enemyLayer))
{
print($"Left Antenna hit {hitL.collider.name}");
}
do this?:
if (Physics.Raycast(antenna[i].agentPos.position + antenna[i].offset, -antenna[i].agentPos.right, out RaycastHit hitL, .75f, enemyLayer))
{
print($"Left Antenna hit {hitL.collider.name}");
}
Yes
Was this supposed to solve the issue, or was a code esthetics thing, because i'm still getting the same result.
It should now be following the rotation of agentPos at the time that raycast happens. So if that object rotates, the rays will rotate as well
Pre-emptive layer mask mistake detection: make sure your enemyLayer variable is actually a layer mask, not a single layer number
maybe I'm missing something
Those do seem to be rotating as the box does
Ohhh I think I may have asked the question incorrectly
I meant like they literally move as the box rotates
How can a beginner in 2D AI, go about making an enemy that can chase the Player even when the Player jumps to higher ground? (No help needed for Horizontal Movement)
I essentially want these raycasts to function as axls, the rotation part was already working as I expected
if you want simple one, you can use points at the corners to to some type of curved lerp to.
but its not very dynamic
Do you mean adaptable?
So, rather than having them at the position and rotation of the base cube, you should make empty child objects at the positions you want the rays to start at. That way when you rotate the parent, these spots rotate with it
Then you'd use one of those spots instead of agentPos
The whole map is off of square Tilemap. If it works for that, then it should be enough
Ok, that makes sense, I'll give it a shot
You could even make it so they all point forward or up in the direction you want, so you would no longer need leftRay and rightRay, you can have each ray just pointing in its own forward direction
yeah but for generated levels wont work well
All my levels are made by hand. It wouldn't be an issue. How can I achieve what you recommended?
when your enemy gets close to one of those edge positions point, it checks the Y of player to which next edge pivot to go to next
but this won't take into account complex pathing
I don't really understand what complex pathing you mean?
You could probably do a*
Going around corners or moving AWAY from the player to get around a "local minimum" distance area (like a U shape)
like a* would help but being sideview introduces complexities than topdown say
🤔 @rich adder Where could I look more in depth on the solution you gave?
curved lerp Enemy AI. Is that it?
trajectory math
This is my attempt at a Mario AI using a path-finding algorithm called A*. The bot won both Mario AI competitions this year!
You can see the path it plans to go as a red line, which updates when it detects new obstacles at the right screen border. It uses only information visible on screen.
At the "close call" situation: In this version of Mar...
its not direct code but more or less explains such an approach
Thanks for sending more information. Really appreciate it 🫡 @rich adder
hi there, idk why im getting this error, its at line 70 in my gun script
this is line 70 as it wasnt in the picture
new bullet doesn't have Bullet script on it
Either newBullet is null or it doesn't have a Bullet component on it
The bullet prefab should probably be of type Bullet so you don't need to use get component
the bullet prefab is just a model of the prefab with a rigidbody and bullet script
newbullet does have the bullet script on it too
im confused
So then you should make bullet of type Bullet instead of GameObject
In that it will prevent you from attaching a prefab without that component on it, yes
can i make this so the run animation only kicks in when shift is held and the player gets a speed bost
but when im instantiating it i need it to instantiate the whole prefab not just the script
You would need to use the BlendTree parameter somehow
it will
Instantiate spawns an entire object
like this?
The type just determines what is returned
yes
Do you still get the error
Then bulletSpawnPos or gun is null
dont seem to be
ill check again
improvements
its spawning now
now i get an error on line 20
have i not grabbed gun correctly
gun is not set before this object exists
Awake runs, then you set it. This shouldn't be in Awake
make an Init method
Or just use Start
never heard of that,i was gonna use ienumerator
i havent coded for long in this language
start works?
Yes
i thought start played before anytjhing else
oh its not like a special method, i meant just as a setup method, but yeah this way works very well too
Hello can someone tell me why my mathf.clamp() is not working properly? Here is my code and logs https://hastebin.com/share/laqeqovite.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
ill look into inits later then
sounds useful
Clamping rotations does not work like you'd expect because you have no idea if a value is something like -30 or 330 which are both the exact same angle
Yes. Angles are a circle
How would I do otherwise
yeah basically something like this
Bullet bullet = Instantiate(etc..)
bullet.Setup(this);
//in the Bullet.cs
private Gun gun;
public void Setup(Gun gun){
this.gun = gun;
//setup rest of stats from awake
}```
It doesn't work when I use if/else statements (for the same reason I think)
You could convert it into 0-360 range by doing (angle + 360) % 360 and do two separate clamps against positive values
so simple yet i would never have thought of it hahaha
thanks for showing me
No worries, takes some time and practice, as time goes on you will write more simple code to the same issues 🙂
Why two separate clamps though, wouldn't I only use one after I convert it
i hope so, im ashamed to say the only languages ive learned before this one is lua and python 🤢
haha yeah had to play around with lua back in gmod server/modding days but yes, I found it "difficult" which is funny considering i find c# easy
Well, let's say you want to have it between -30 and 30, the value 350 is above both when converted into 0-360. You'd want to check to see if it's above your lower bound, then below your upper bound. You basically need to do an anti-clamp, it needs to be anywhere but in between those two values
Umm I'm not sure I understand what you're saying sorry
Like, I would need to check it before I convert it?
So, again, let's assume -30 to 30 is the range you want. You'd need to convert the angle into positive values as I said above, but you need to check if it's below 30 or above 330
Clamping between 30 and 330 would get you if the number is above 30 or below 330
So since there's not an "inverse clamp" the best way to do it is to just do two checks
i liked it until i realised i actually hated it
mainly because i was using it for roblox lol
ive never gotten into modding
is it fun?
I'm so sorry but I don't get what you're saying. I think I'm just gonna try to have it limited between 0 and 20
Is that the actual value you were originally trying to do
if you enjoy the game enough to mod yea, also modding source SDK got me into looking at a game engine, unity felt more comfortable
I wanted to have it between -20 and 20 so 20 and 340?
Yes, so you'd need to check if it's less than 20, or if it's greater than 340
and then convert it?
thats nice, c# has been fun, i tried c++ and stopped quickly. I still dont even get singletons anyway so it a bit above my level. have u evver used any other engines?
Same on singletons. Heard it tossed around a few times. Sounds like some kind of global static object or something?
You'd take your current rotation angle, add 360, then mod 360. The angle is now in the 0-360 range
then you check if that angle is below 20 or above 340
If it's not, then set it to whichever of those is closest
I've used Game maker a lot back in the day, also playaround with Unreal.
tried godot but didn't offer anything new. but yeah probably going into offtopic territory here so lol
Isn't that one clamp though
honestly idk, delegates and singletons are mentioned enough for me to be annoyed that i cant understand them but i havent come across a time where ive actively searched up how touse them unless its out of my own interest
How would you write that as one clamp
well thanks for the help anyway
I've kind of got delegates figured out, but that's thanks to modding another game lol. One that uses unrealscript of all things XD
like blueprints?
I suppose you're right actually
Wait
Ik I have it open too
are they actually useful though? should i go out of my way to learn delegates as a moderate beginner
Ehhhhh, not really. They're really nice, but unneeded
gotta search what u dont know, from google:
When we say two pieces of code are “decoupled”, we mean a change in one usually doesn't require a change in the other. When you change some feature in your game, the fewer places in code you have to touch, the easier it is.
^ That gets important as your game's infrastructure gets larger. Idk how big that's gonna get for a beginner
true but also best learning good practices early too
for example a score Logic script should have no idea about a UI score display script
UI Score script just "listens" to events thrown by the Score such as Updated score event to refresh the UI
imagine you put UI inside the score script too, now you need UI every time you want to test logic for score
ive been doing that a bit but never knew thats what decoupling actually meant
isnt that kind of like interfaces too? with functions
i love interfaces so much
but yeah as beginner don't worry, its good making mistakes so we learn WHY something else is better to use instead
thank you for the advice
Wouldn't I need to use an if/else statement for this though
Yes. If it's below 180 but above 20, set it to 20. If it's above 180 but below 340, set it to 340
Okay thanks
what does this mean?
like i know the value is null
but im unsure as to what value is null
and it wont show me what is null and where
Question on structuring audio for killing monsters; Do you:
- assign an audio source to each of the many monsters, each audio source with an instance of the asset audio clip, and then play the clip when the monster dies; or
- create one audio manager, and when a monster dies, ask it to spawn a new audio source at that location and play the clip; or
- create an audio manager with a pool of audio clips, and move a pool instance to the location of the dying monster; or
- something completely different that I haven't thought about.
#3 for sure. Unity also has a built in object pool you can look into using.
Wait so how would I even use a clamp after this because wouldn't it already be in between 20 and 0 or 340 and 360 after the if/else statements
You wouldn't. No clamps required
But you said I needed to use two
anyone know what could be happening here?
i think its because they are set first then immediately turned off, which could be causing the error
Yes, these if statements. These are your clamps
You don't actually call Mathf.clamp, you do the math manually
I mean, it says the issue no?
You're trying to do .PlayOneShot on a clip that returns null.
double-click the error, it should enter your IDE
you'll see what's null.
fixed it by doing
private void Awake()
{
_audioSource = FindObjectOfType<MenuManager>().GetComponent<AudioSource>();
}
instead of start i did awake
fixed it
Just as a general guideline, you want to avoid using FindObjectOfType unless absolutely necessary. It's not a very great practice.
Yeah i know
I'm saying this as a general thing - if it works in your case that's fine.
it is absolutely necessary in this case
i guess the object was inactive at start time
so doing it in awake fixed it
Seems like you could just use the Singleton pattern for this
it definitely doesnt look necessary here. dont these objects both exist just in the scene? You could drag it in. Or use singleton
there are multiple menus in a game
so idk if singleton would work
that should be fine.
Then FindObjectOfType won't find the right one always either
theres only one in a scene
but multiple in a session
Then Singleton works
Just not DDOL Singleton
oh i thought singleton was for like DDOL stuff
The basic form of Singleton just has the static accessor, DDOL isn't required
DontDestroyOnLoad
ah
i see, either way its not mission critical so this implementation works fine even if its dirty
althought i recognise it is better practice to use a singleton in this case
If I have an instance variable in my abstract class, why doesn't the inherited class include that in it's scope? I can only modify baseclass in the Awake/Start... methods, but not in the variable declaration area.
usually you modify parent variables in the constructor but since you can't really use one with monos that's why you're usually using awake or start
or make a custom initializer method
ok, I guess that makes sense.
It needs to be in a function
You can't override things in the declaration
you're trying to initialize the inherited variable in the class scope . . .
also, you're missing a Vecttor3Int in one of those lines . . .
oh the compiler told me I dont need it because it was implicit
i wiped the rest of them too
true, but you should do that for all of them . . .
yep, exactly that . . .
yeah, i was trying to see the compiler suggestions about the other error and it tossed that one at me too
For some reason, my knight class thinks it's special, because it isn't creating the polys it's meant to. I am calling the exact same method on all of the classes in the same manner, and I've even setit up so that the instantiating of the poly is done in the abstract class that's inherited by the subclasses just to ensure a consistent result.
Of course, everything was consisten except for the horsey.
it would appear that basicHexMoves is empty
Debug.Log to double check that
or perhaps we're looking at the wrong code
!code is a better way to share
📃 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.
https://gdl.space/egumehujoj.cs
You are correct, that the debug.log is saying hexmoves is empty. In fact I debugged the start method of the knight:
https://gdl.space/wiwabayebi.cpp
And it's not even adding the vector3ints. It' s just ignoring the assignment.
I am calling the instantiate method the same way for all of the classes, though the abstract parent class:
https://gdl.space/epoyetazud.cs
the CubetoQuad is for thoroughness
https://gdl.space/igowiqiwet.cs
my bad on the code flood tho
what's really messing me up is the fact that my program is literally ignoring me
It's unclear where InstantiateMovePoly() is defined
it;s in the chesspiece method too, that's how I call it in start()
that's the full chesspiece method
and Knight?
https://gdl.space/wiwabayebi.cpp
that was the full knight
there isn't much in there
Ok so this logs what exactly again?
like what does this log?
Debug.Log(name + "\n" + basicHexMoves.Count);
and
Debug.Log(name + "\n" + basicHexMoves.Count + "\n" + moveIndicators.Count);
What's the difference between a trigger and a boolean as an animator parameter?
Aren't they both just a toggle?
Oh, so trigger cannot be dissabled after called once?
Debug.Log(name + "\n" + basicHexMoves.Count);
The log in the knight statement verifies the length of the knights hexmove list. It's right after the assignment so I can verify that the assignment happened correctly
Debug.Log(name + "\n" + basicHexMoves.Count + "\n" + moveIndicators.Count);
The log at the end of the InstantiatePoly() method verifies the length of the hexmove list for all pieces and verifies how many move polys I create for each of them.
That's basically what I am doing rn, but isn't that just make it not loop time and done?
ye, got to probably add some exit time to them too so they don't fallback to your other animation state instantly
I'm asking what it printed
not what they do
The assignments fail immediately in the awake method, which leads to empty lists for them in the instantiate method
That's basically build in in the animation itself, it has a downtime in which it recovers from the attacfk
basicHexMoves = new List<List<Vector3Int>>();```
it's because you have a semicolon here
If I want for them to transition from ANY point of the idle state to the attack state, I have to dissable exit time right?
Else it waits for the end of the loop isn't it?
Collection initializers don't have a semicolon like that:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers
not really played with animation stuff for a while but I usually wouldn't add exit time to loops so you can exit it instantly, but sometimes like attack animations you do want to interupt if you were attacked and stuff
that's the first time I've put a semicolon that wasn't supposed to be there. usually I forget to put them where i need them.
Do you happen to know why the code doesn't throw an error when declaring a bunch of new lists without identifiers, since the semicolon was separating them?
Because new List<Vector3Int>() { new (-3, 2, 1) }; is a complete, fully valid line of code that happens to do nothing of use.
A real collection initializer uses commas and curly braces:
List<Cat> cats = new List<Cat>
{
new Cat{ Name = "Sylvester", Age=8 },
new Cat{ Name = "Whiskers", Age=2 },
new Cat{ Name = "Sasha", Age=14 }
};```
oh, cool
This is just a guy that floats around randomly and at random intervals does a superfast spit with barely no telegraph. So pretty sure this is not meant to have exit time
yeah but if it's a trigger animation without exit time I'm pretty sure it falls back into the previous state instantly without it or maybe im mistaken
I usually just try to use booleans if possible since I like that control better
https://hastebin.com/share/ofidogihaw.csharp
Im getting this error msg when swinging at my enemy, how can i fix this?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
not everything in the hitEnemies array has an Enemy component
is it because my enemy has a bunch of children
if those objects are on whatever layer is included in the raycast, then yes. you'll want to use TryGetComponent to check if the object has the component if you don't want to change the layers on those objects
also consider using the NonAlloc version of the query to reduce your garbage generation
each child object under enemy has the enemy tag
it's the layer that matters, you're not doing anything at all with tags
yes, i gathered that. hence my suggestions
how would i use trygetcomponent in my script?
check the docs to see how to use it https://docs.unity3d.com/ScriptReference/Component.TryGetComponent.html
im looking at it, im still confused on how it works
whats confusing
the doc shows exactly how to use it, should be easy to implement into your script
i am just lost on what to replace in my script
your using GetComponent, you need to use TryGetComponent
thats what your replacing
did you not look at how it works
you cant just replace it 1 to 1, look at the docs
the docs for GetComponent and TryGetComponent are completely different
Can I check if a local parameter already exist before creating it?
you dont need the <> part if you specify type by the out keyword
idk why its in the start method, anyway now change it to your components
because they literally copy/pasted the whole example
you also need to call TryGetComponent on the colliders in the array, not on this component
Like let me explain, I have a parent general class for enemies that gets the player position in Update and sets other basic stuff with it. I want all that to happen AFTER some modifications in the Update of the specific enemy (that also need the player position), so I am calling base.Update() after that but I don't want to calculate the player position once again at the base.Update() if I already did before, is there a way to do this with a variable inside update itself or it NEEDS to be a class parameter for that?
i dont know what usespring = false; would equate to in my code
that would be TakeDamage(attackDamage);
you definitely should take a beginner C# course
im in one now, but ive never dealt with trygetcomponent before
its the same thing as get component , you're just accessing stuff with .
same thing
Enemy e = enemy.GetComponent<Enemy>();
if(e != null)
e.DoSomething();```
as
```cs
if(enemy.TryGetComponent(out Enemy e))
e.DoSomething();```
I think what you're describing is better done with overriding methods instead of overriding update
because your 'base' update will always call the most derived method if it's overriden
I am trying to add a force that would push my object forwards depending on the angle its rotated
2d btw
but i can only seem to get it to go straight up and im not quite sure how the addforceatpostion function works
just use normal AddForce? why do you need the atposition one?
also show your code
void Update()
{
if (Input.GetKey("w"))
{
rb2d.AddForce(Vector2.up);
}
}
your only making it go up, use transform.up to get it from the actual object not just a static direction
ohhh
thank you
I have another question, right now im using addtorque to change the rotation of my player but how can i do it where it stops immediatly after i stop changing the rotation and not continue to rotate
Debug.Log("( ${x}, ${y}, ${z})");
how do I get the values from variables like this?
Dollar sign goes on the string, not in it
oh wow that beautiful
thanks
Do you need to use add torque? Usually it's fine to just directly affect the rotation with the values you want especially if this is just a capsule.
Otherwise you can set the angular velocity
Meant to reply to you
just wanted to say i figured it out, thanks for the advice
If I want this to Translate locally I have to pass it the parent right?
I'd do a
considering that second parameter there
Is kinda hard to see with what I am trying rn, but sure
This is the pattern I am seeking, which I assume is best done if I just parent every bullet to an spinning empty parent and move them forwards locally
Is it? XD
sounds probably right then
transform.foward is always considerd relative to itself such that it's a direction its forward direction is pointing to
such that you should just be able to refer to its forward and use world position local/absolute units to go in the direction it's facing
Is basically that the world itself is the parent if there is none given
eh, I don't really think of it that way. Tranform.Forward just uses the object's orientation as is, such that you can create a direction from the coordinate system its composed of
so no matter where it is in the world, transform.forward will always just go in its own forward direction
I don't really use transform.Translate but it sounds like you just refer to is own object space and then use absolute units
otherwise you do something like transform.position(Transform.forward * speed * deltatime)
What can cause this? I have gameObject.SetActive(false) in a MonoBehaviour, and it only deactivates the current script, not all the GO's scripts and the children.
I need help fixing this i have no idea how this works
Assertion failed on expression: 'CompareApproximately(SqrMagnitude(result), 1.0F)'
UnityEngine.Quaternion:Internal_FromEulerRad (UnityEngine.Vector3)
Test:Update () (at Assets/Test.cs:28)
float angle = Mathf.Atan(rb2d.velocity.y / rotate) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
nevermind It's because i forgot to set the variable rotate to something
that's the normal behaviour
Hmmm, that should not deactivate a script. Just the gameobject. And if it has children, those too.
Can you share more of the code?
MyScript.enabled = false would do that. But not gameObject.SetActive
Deactivating a GameObject disables each component, including attached renderers, colliders, rigidbodies, and scripts.
so it would deactivate the scripts on the GO
but the children should become inactive too yeah
Correct
They are saying it is ONLY deactivating the script
void Update() {
if (_hasHit) return; // spurious
_life += Time.deltaTime;
if (_life > _pld.Lifetime.Value) {
gameObject.SetActive(false);
}
RaycastHit2D hit = Physics2D.Linecast(transform.position,
transform.position + Direction * _lookforward * Time.deltaTime,
(1 << LayerMask.NameToLayer(UnitManager.LAYER_PLAYER)) | (1 << LayerMask.NameToLayer(UnitManager.LAYER_ENEMY)) | (1 << LayerMask.NameToLayer(UnitManager.LAYER_NEUTRAL))
);
if (hit) {
if (hit.transform.gameObject.TryGetComponent<HealthCapability>(out HealthCapability hc)) {
_hasHit = true;
enabled = false;
transform.position = hit.point;
transform.GetComponent<Rigidbody2D>().velocity = Vector3.zero;
hc.DecreaseHealth(_pld.Damage.Value);
// show explotions
Instantiate(_pso.explosionPrefab, transform.position, Quaternion.identity) as GameObject;
// play audio
AudioSource audioSource = gameObject.GetComponent<AudioSource>();
audioSource.clip = _pso.soundExplosion;
audioSource.spatialBlend = 1f;
audioSource.maxDistance = 100f;
audioSource.Play();
gameObject.SetActive(false);
}
}
}
Correct, it is only deactivating the script.
Btw. I understand that deactivating right after Play() means that the audio clip is not played.
show your hierachy of gameobjects (where it shows which ones are active and not active) after this is called
Found the many bugs:
- I disabled the script separately (
enabled = false) - I didn't reset
_hasHitwhen I returned an object to the pool
Consequence: the object that had hit had the script disabled and had never hit anything anymore, because of the check right at the top of update().
object pools are fun
{
if (outlineColor == Color.white)
return;
outlineMaterial.SetColor("_Color", outlineColor);
outlineMaterial.SetFloat("_Thickness", highlightedThickness);
outlineMaterial.SetFloat("_ColorOverlayActive", 1f);
}
private void OnMouseExit()
{
outlineMaterial.SetFloat("_Thickness", defaultThickness);
outlineMaterial.SetFloat("_ColorOverlayActive", 0f);
}```
Any idea why this would be causing my object to flash?
either always manage the scripts / gameobject state from the same script
or add lots of comments 🙂
I only implemented a simple pool (standard array with iterating over it to find a non-active GO). Need to look into the provided ObjectPool<T>. But the many callbacks look intimidating at first, even though they make sense.
What's with the if (outlineColor == Color.white), OnMouseEnter will only get called once anyway
Also seems like you don't remove the color again on exit?
Is this script on the correct gameobject? Are there any other scripts interfering?
that first bit was so if i dont apply an outline color with item rarity it just never enables the outline
i disabled any other scripts that could interfere i think, ill check again
it grabs the outline color from the scriptable object so the color.white (default) is just so it doesnt do weird stuff if i forget to set it
but the return prevents the rest of the OnMouseEnter to execute
for some reason when i press the console key and call RunCommand, it is not able to match the command entered to one of the commands in the array. it will log in the console the "no such command" message, and even include the command in the message that should be getting found successfully but for some reason isn't.
using System.Collections.Generic;
using System.Data;
using Unity.VisualScripting;
using UnityEngine;
using TMPro;
public class ConsoleController : MonoBehaviour
{
[Header("Keybinds")]
public KeyCode consoleKey = KeyCode.BackQuote;
[Header("Command List")]
public string[] commands;
[Header("References")]
public TextMeshProUGUI commandLine;
bool showConsole;
void Update()
{
if(Input.GetKeyDown(consoleKey))
{
RunCommand(commandLine.text);
}
}
public void RunCommand(string command)
{
foreach(string s in commands)
{
if(s == command)
{
Debug.Log("Command Found! Command: " + s);
return;
}
else if(s == commands[commands.Length - 1])
{
Debug.Log("No such command '" + command + "' found!");
}
}
}
}```
that is my full class, not sure what's going on
i will note that for some reason, if i manually set command to one of the commands in the RunCommand function, it works correctly. but it doesn't work correctly when getting the string from a tmpro input object
look at your logic in the if statements, they dont seem right.
foreach(string s in commands)
...
if(s == commands[commands.Length - 1])
as for why its not working, try printing out the actual results like
Debug.Log($"Command {command} Comparing to {s} Result {s == command}");
found the issue lol
wasnt even a problem with the code
the Z was just 0, which was also the layer of the background png
so it constantly swapped between
well i was using a TMPro input field but i was referencing the text object child of the input field. when i instead switched to referencing the input field itself, it started working. strange
not entirely sure how tmpro handles that stuff, but some basic debugging should've pointed you towards that the input was flawed
also, you can do if(commands.Contains(...)) using Linq
The text object in input field has an invisible character at the end of its string
That's why your string comparison wasn't working when you were using the text from text object instead of the input field
Hey guys, I wonder what if I serialize a list of scriptable objects into json.
And when i deserialize it, what do I get ?
Say i have a class
public class Demo : ScriptableObject
public List<DataSO> listOfLust;
After deserializing, do I still get a list or what ?
how 2 fix this text? autosize is already true
You get back whatever type you specify it as, or even a less derived class if you wanted
and yes, you can serialize scriptable objects usually
Thanks
Though, you don't actually want to deserialize/serialize SOs but rather you should be id-ing them and grabbing the pre-defined instance from your assets. Assuming you aren't writing to your SOs
So my goal is just to program Minesweeper so I can figure out the basic tools because I already know how to make the actual algorithm for generating a Minesweeper board
I've run into 2 snags though:
I need a way to have the camera size up enough to capture the whole board regardless of the size up to the max size I'll allow,
Second, I'm running into an issue with the board... losing detail when the camera gets large enough I think?
Here's the board 9x9 with camera orthographicSize 5
It looks a little trippy because I slapped the sprite together in like 5 seconds
Here it is 13x13 with size 7 though
Some of the lines are losing visiblity, and the problem worsens as the camera gets larger
is it a texture? Could be mipmaps related
maybe something in cameraObject.GetComponent<Camera>()?
stop, i understoodproblem
I have a GridManager object that uses a Tile prefab object I made, and that Tile object has a SpriteRenderer with a 1200x1200 sprite scaled down to 0.09 in all dimensions
maybe, you will make some lines above field?
Like... have the lines be separate objects from the tiles?
I would just tile a texture and use the tiling and offset values of a shader
usually they comes with unity's default shaders
you can use any image as texture & add it to tiles
& image will become a material
sprite import probably has some similar options if you don't want to do it via shader I guess
shader stuff just easier to manipulate at runtime
I just didn't know it was an option and I'll need to research how to do it
I think the idea here is you shouldnt be moving the camera, but you should be tiling the texture differently
It does sound like a better plan for retaining detail I imagine
I'll give it a shot
Thanks
that would probably be the sprite way to tile, or just use repeat/wrapping mode?
https://learn.unity.com/tutorial/shader-graph-tiling-and-offset-2019-3
otherwise this node is on most unity shaders in the material options (or include it in your own shader if you want)
Script error: OnTriggerEnter
This message parameter has to be of type: Collider
The message will be ignored.
why am i getting this error
{
if (other.tag == "Pickup")
{
Debug.Log("woking");
endOfConveyor = false;
approve.interactable = true;
deny.interactable = true;
baggageInScanner = other.gameObject.transform.parent.gameObject;
}
}``` thats the method its talking about
Well what do you think the solution is ?
I looked it up online and it was that the parameter should be collider not collision and i havent got collision so idk
Think a little about the error msg. It says it should be of type Collider, not any type of collider.
Collider and BoxCollider are not the same type.
But i need to distinguish between box and sphere tho as i have more than one on the gameObject
Ah Uri, you never told me how to send my data over the network if not in a dictionary.
Why is it bad to use a dictionary and what is the alternative?
list of structs
Are both triggers ?
I never told you dicts were bad all I was saying was that I think you are sending too much data over the network
Yos
but how do I send less data then 😦
bulk of what I send over networks are usually just ids
some vectors and whatnot... but im talking about a crappy vampire clone and shooter arena ;)
look at other.GetType() == typeof();
I would just separate the triggers into their own gameObjects and have a script for each
Like I said you would send a itemId and the relevant generated stats. Anything that is not random the client can reconstruct when creating the object on his side for example having the item start with 100% durability.
yeah that's what I'm doing, it's just structured in a dictionary
I believe last time we talked you were sending pretty much the entire item serialized as json.
yeah because there's a lot of generated stats on the item
surely other players can also generate the same thing then
it's multiplayer, needs to be generated by the server
definitely not
Look if it aint causing network traffic issues and it works it works right hah. I suppose generating items is a rate enough event.
I just thought there was something wrong with sending a dictionary structure over the netwerok
Depends on your dictionary I suppose
if you are thinking that as a security issue, then whats to stop someone from just modifying the string they receive?
it's item with randomly generated stats
if I let clients generate them, it's easy to cheat max stat items
how do I make cinemachine camera orbit around a target?
i can guarantee you its as easy in your current method compared to what I am saying.
i've been fiddling with this the whole day but the camera just refuses to do so
the items are stored in a database, only accessible by the server
combat is also generated by the server
so yes, you could alter your item client side, but nothing would change
What are you saying, that your method is currently hacker proof? Because regardless if you send the full item string (i think you were doing this as json?) vs sending a number for them to use in generation. both will be easily modified by people who want to modify it
I'm saying it doesn't matter if they modify it client side, because everything happens on the server and the server doesn't accept any client data
orbit it via user input or just by itself? Theres the freelook camera which allows for it
If it doesnt matter, then exactly why does it matter if the user generates it for themselves based on a seed compared to sending them the full string?
because I want to display the item data to the user? 😛
When you say items are generated, you mean randomly right?
Or these are all just preexisting items already declared
then whats stopping you from just sending the user the seed and having them generate the item data with the same algorithm the server used?
that is actually a really great idea
That is what ive been saying from the start
thanks for explaining it 🙂
your server should be generating everything and giving it back
unless you dont* really care about clients bsing about getting the best rolls possible
theres really no difference in this case
i vaguely remember what they were doing but i believe it was creating a json string from their item information. which was like a dictionary in a dictionary or something.
Theres literally no difference if someone wants to modify that string compared to modifying the seed they receive
you'd still verify it, not like when you smack a mob the server does going to look away when the client hits it for 1000k damage
yeah it's a dictionary containing 2 dictionaries
one for the combat and one for the items dropped
but in both cases I can just send the random seed and then let the client calculate it by itself
should solve a lot of my issues 🙂
that verification still doesnt affect if the client or server generates something. its really nothing if the client generates something wrong intentionally while the server has its own correct copy. Because itll be using the correct information in damage and other things.
Ive played a few games where they really dont care what you have or see client side, because its not like you can do anything with it. I've tried a lot to actually do something with it too, but the game just didnt care
that's exactly what I'm going for 🙂
seems like that would cause a lot of desync issues
idk, i'd just ask the server hey, I'm rerolling my weapon mods can you do it for me
to be fair, you cant really complain about desync if you're trying to hack
only way there's desync is if the server & client have different generation methods, which I guess could happen lol
The 20 year old game osrs has massive desync issues, that you kinda have to intentionally cause. they really dont care, you just get booted off when that desync eventually causes an error clientside
other competitive games have it too, which arent intentionally caused but sometimes by lag. Nothing you can really do. Best not to worry about hackers unless you're making the next valorant
bawsi is there a simple way to use one random seed to generate different randomized results?
say we fight a monster, I need player damage, monster damage, experience gained, item dropped
can I easily use 1 seed or would it be better to send 4 random seeds?
Pretty sure they just have a lot of malicious attacks. The game is incredibly optimized in terms of networking capabilities
A single Random class works fine
If you use a set seed then the result will be the same each time
Nowadays there's Random.Shared for a shared random class because there's no point in having 4 different classes for randomization
IDK if that is in Unity though
yea single seed, but this is probably gonna lead more into a #archived-networking discussion because you also have to make sure everyones generating it in the same order. Otherwise this will be a desync issue
ah there's no real multiplayer, the clients do not communicate with each other, only with the server
and not all that often really
how should I setup skill trees to work alongside the UI? should I just handplace every ability in the tree for each class and then just activate whichever class the player is? or are there any better suggestions
I think I'm not exactly following, atm I'm just doing stuff like Random.next(0, 100)
Yeah that's Unity's build in Random
well theres some malicious attacks but really not much since they "fixed" the server crashes associated with it. also a TON of bugs which abuse their system.
There's two, idk why Unity has one
are these predetermined? Itll probably be best to just do this by hand if so.
The UI can also just have handpicked locations for where the ability goes, which takes in an array and places them in order. Then link that array to your players abilities
depends more so on how the player even stores abilities
that's really up to preference. If there's endless/randomized skill trees I'd go with auto-gen, but otherwise handcraft it all
or go half way and handcraft a reusable template
Would splines or a grid system be more efficient in making a conveyor belt system?
what do you mean with the same order?
does Random have a way to generate multiple random numbers from one "seed" or something? are different parameters possible?
you are generating multiple random numbers, by calling the functions many times. You can change the seed here
https://docs.unity3d.com/ScriptReference/Random.InitState.html
though I would just use the c# random class, you can also provide a seed in the constructor
https://learn.microsoft.com/en-us/dotnet/api/system.random?view=net-8.0
If you provide the same seed, it will always generate the same numbers in the same order
would it work with parameters if I want to generate a number between certain values?
like mindmg = random.next(1,10)
maxdmg = random.next(500,600)
Random.Next is from System.Random
So the whole point of it is to have a static reference to an existing feature? I'm confused
Because I was looking it up and apparently it was it's own generator to some people
The point is to have my server generate the random number (or numbers or seed)
and then generate a lot more numbers based on those on both my server & client
I'm saying that it is System.Random.Next, nothing to do with UnityEngine.Random
Then I got confused because he capitalized the wording, assuming it was some static class
Either way my point was that I don't see why Unity would have its own Random to begin with 🤷♂️
probably slightly faster, optimized for games
I don't care about which Random class I use though
I'm just using System.Random.Next atm because my server is C#, not unity
Unity Random also has a bunch of useful features for gamedev, such as insideUnitCircle/Sphere
yes, you are always using a seed even if you dont specify one. It would work the same as it works now. When you dont specify the seed, it just uses the current time
awesome 🙂
how 2 fix this text? autoFontSize is already true
Could have just added an extension to the existing class 🤔
Cause its named GameManager
ok
just a fancy icon for that class
also thats a gear

I have a GameManager aswell and mine didnt get that icon for some reason... In the other project I have it does though
Why is that
🔩 u
I don't see a problem with UnityEngine.Random tbh. It also generates floats, not doubles like System.Random
Static random class can be useful, though I often find a need to use instances so that's when I use System.Random
Suppose it mostly boils down to convenience then. I wondered if there was an actual reason apart from that
📃 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.
UnityEngine.Random doesn't overlap much with System.Random.
System.Random lets you get uniformly distributed integers, while UnityEngine.Random is more for floats in closed ranges
you can't get uniformly distributed integers (easily) with UnityEngine.Random since it's closed instead of half-open
Hey so here I have these 2 scripts, which are causing these 2 errors that i have no clue how to get rid of. any ideas?
maybe show the code?
for the first one, maybe follow what the error says to do
yeah my bad forgot to paste the link
yeah the error tells you exactly what to do
and you are trying to assign UIHandler to it
ok
yeah idk what to do to my code
no, not really
ive tried a million and 1 solutions
did you try the one the error tells you to do, first off
it doesnt
GetComponent is a function, you didn't call it
or im dont get it at least
right, but it's a step in the right direction
right i need the parenthesis
that's not what the current error is
not the current error
not currently
one step at a time my guy
i don't think you registered what i said
im not talking to you please carry on
it's not the current error. the current error is that the function wasn't called to begin with. fix that, and get the new error, the one you're referring to, with a more helpful message
is your ide configured?
pretty sure
can you screenshot it just to be sure?
so no probably lol
one sec
once you've added the function call, you'll be able to see another error that you're trying to assign UIHandler to GameObject
you've declared UILink as GameObject, but you're trying to set it to a UIHandler, and you're trying to use it as a UIHandler, so you haven't declared it with the type you actually want it to be.
making it a gameobject was just a test as when i had it just as uimanager it still made errors
just explaining
UIManager != UIHandler though
you're trying to use it as a UIHandler, not a UIManager
its been that long, ive forgotten where to find it again
ide
ctrl + win logo + s = screenshot
huh
i know ho toscreenshot
you asked me to ss my ide
i do
you dont
ok, what is "it" in this sentence
integrated development environment
so why can't you screenshot it
my ide config
i asked you to screenshot your CODE
you were asked to screenshot your ide, not your ide config
can we dial down the rudeness a little pls?
id love that
yup, it is not configured
it is required to have your ide configured in order to get help here due to #📖┃code-of-conduct
!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
• Other/None
!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
• Other/None
Is there info on what order Update()s are processed?
Context (not a problem, I solved it, but I want to understand it more):
I had a 2D camera follow a player, with this logic (pseudo code):
// player
void Update(){
transform.position = new Vector3(...);
}
// camera
void Update(){
tranform.position = playerObject.transform.position;
}
There was jittering when I tested this.
I googled about it, saw some people say use FixedUpdate instead. So I tried that, it helped with the jittering (but didn't completely solve it), and also like now movement is 60fps on my 165hz monitor, it looked slightly off.
Then I remembered LateUpdate exists, I move the camera code to LateUpdate and it worked like a charm
please help me fix this
is this in one script?
basically camera operations should be called in LateUpdate
after the player changes his position
two scripts, one on the player, one on the camera.
i followed thesteps
here is it lacking new input system of unity?
all the Updates are processed before all the LateUpdates, i don't think it's well-defined how 2 Updates or 2 LateUpdates are ordered
I just want to know more about order of operation.
Is there any logic to the order of different scripts' Update() calls, or is there no particular order one can rely on (treat it as if it's random order)?
it is
https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
These are the docs on Update and other similar functions
in script execution order
anyone??
Thx will read
oh sick
I think Update() functions are completely unrelated, so there's no order, but not sure
there is order
that you can set
anyone please help solving this issue
did you install the module
stop spamming man
yeah
help🥹
nothing changed
how? 😮
have you tried recompiling after that
do i need to download new input system?
doesn't seem like it's mean for the Update function though?
Would you be able to make a specific Update function of one script consistently run before/after another one?
Wouldn't it depend on the time it takes the function to run?
Hi Guys, I have added RB and the bounciness Physics material to the ball object, however, the balls are stacking on top of each other, I want them to interact and fall just as normal, how can I make it happen? Please excuse my language.
should i click regenerate project files
the package, yes
from what, exactly
okie
how to make buttons scale with screen size
https://cdn.discordapp.com/attachments/1217805647463055453/1232251794910871553/image.png?ex=6628c76a&is=662775ea&hm=0b2bbf6952dd592e67913a1d71ab6b923f7920195afffa15c21f8fca7b18557f&
https://cdn.discordapp.com/attachments/1217805647463055453/1232251885595918388/image.png?ex=6628c77f&is=662775ff&hm=54c9263618f0a9e8cc8715528561d2d7fe298f28312c08718afa6c99283dbdd3&
Are you using VSCode or VS? And would you be able to switch to VS?
VSCode's configuration is annoying
i figured it out nvm
Either way your syntax should be properly highlighted so if this is not the case follow the steps again and perhaps try a restart
Can someone please help me with this?
user input, i intend to make a 3rd person camera
you're clicking in the same spot, so they're spawning at the same spot, so they're perfectly aligned and balanced. nothing's wrong with your physics
freelook camera should just do what you need then
maybe you could add some variance to the spawning to make it improbable to spawn in the same place?
this is probably due to the settings you put on the physics material, not really a code question though.
I'm trying to make it work like how the balls are falling realistically in above video clip, I clicked on the same spot as on my other video but in this video, you can see that the balls are falling down normally but in my first video, the balls are stacking
that looks smaller, perhaps it's having some floating-point stuff so it's not perfectly aligned
is this video from like a tutorial you are following? Try doing the same without a material at all, and see the result. Also its a lot better if you show the settings you have for the rb and material
it seems that my camera is being clamped orientation wise but i don't know why
Yes, I'm taking reference of the above video and here is the SS of both RB and collider components of the ball object
I'm not really sure what you mean orientation wise. There are lots of settings on the component, play around with them
nvm figured out why#
Perhaps compare the position of the ball against the one below it on collission and if they match perfectly (with some tiny margin of error), apply a very small amount of horizontal velocity in a randon direction on the upper ball
The physics makes sense here
in my infinite wisdom i might have accidentally clamped the camera and prevented it from moving at all
It's just super perfect here with where it lands which is unrealistic
Can you show the physics materials settings?
That's weird, I wouldnt really expect this with circle colliders but I dont do 2d. Maybe try to play around with the settings like a higher bounciness
Obviously can be done with code solutions but you mightve missed a step when following the tutorial. That part is more concerning to me that it's not acting exactly like a video you're following
I'm not following a tutorial to make it, I'm trying to create on my own keeping that as a reference and thank you, I'll keep trying different aspects, maybe that will help me figure out. Thanks to @eternal needle @burnt vapor @naive pawn 🙏
btw this was directed to you, in case you missed it
That will affect the actual gameplay I believe since the game requirement is to fill the container so if I modify this way as suggested, it may make it more difficult to instantiate the balls to drop inside the container
it could be so small as to be unnoticable, just so they aren't perfectly aligned
a gaussian distribution perhaps, but even a uniform distribution in [-0.001, 0.001] would probably be fine
Will try that as well, maybe as you suggested, it may help me get the output I'm expecting... Thank you once again 🙂
is it preferable to have everything on one canvas or have many canvases
You definitely dont need any statistical distributions here. Even just a unity random range (-0.001, 0.001) will be fine.
any reason you're asking? both are fine
just wondering how I should construct my UI, redoing it cause its a mess
well it depends on your UI lol
I have my real UI on a single canvas
but each monster healthbar has it's own canvas
kk, thanks
I think in most cases a single canvas is easiest
It’s preferable to split ui into many (sub)canvases and group widgets that change together on one canvas. Your layout needs may also dictate where you can use separate canvases.
I believe there is something pinned in #📲┃ui-ux about it.
ah nice to know
thanks
most of that probably doesn't matter for a small game though
how 2 fix this text? autoFontSize is already true
Yoooooooooooooooooo, I have an inventory system with items that ALL have a different use case. Generalizing them into different classes like WeaponItem and ArmorItem wouldn't work. Should I just create a different class for every item and let them inherit from ItemBase or is there a better approach?
What do you mean by use case ?
Just usage for the player, all items have different interactions which cannot be generalized
Well there is nothing wrong with several levels of inheritence like ItemBase-WeaponBase-m4a4
are they all completely separate though?
they would still have general or common attributes like damage and speed, no?
even stuff like equipping or putting them in an inventory.
those can be in a common parent class
if they're all "weapons" in a way a player can understand, then they can be handled the same way in code to some degree
ItemBase is a good idea, and even a more less* derived based for serialization purposes perhaps?
otherwise can use interfaces for that if you want
if they can't be generalized at all that would just be an incoherent system that would be hard for a player to understand.
this is a code channel bud, delete and ask in #💻┃unity-talk .. showing screenshots of before and after.
My current approach is to use a combination of inheritance and interfaces.
Sword should extend Weapon should extend Item.
This way, things like your inventory can simply hold Items.
However, to provide functionality, I use interfaces. So perhaps any item that can be equipped would implement IEquippable
Hi. Can I write here my problem, when I wrote early in code-general branch to get help asap?
please don't crosspost
well. Delete there and write here?)
no, you might want to rethink your question, I read it and have no idea what your problem actually is
when I change the size between the scene and the project window, red lines appear, the buttons break up and it affects when I start the game and the buttons there also change, but I don't change their size, I just want to make the scene window smaller
you didnt properly set your anchors, i would assume
dont post that here, update your original question in the other channel
solved, thank you
Do you use Scriptable Objects or just Classes
Yeah ScriptableObjects for my items
I have it like
BaseItem
_EquipableItem
__Armor/ Helmet
So instead of an interface the equipable items all derive from EquipableItem first
Not sure if that was a good idea or if I should also use interfaces
This is a classic pitfall
Going to bite you in the ass
Get rid of the inheritance, use composition and tagging
That's my suggestion
What do you mean with composition/ tagging?
Completely remove inheritance?
In-built tagging or a custom implimentation?
Custom obviously since these aren't GameObjects
how to solve that combined mesh problem?
Composition meaning the item would have something like List<Effect> or List<StatBonus> to satisfy equipping or consumption.
hmm I will have to read up on it
Where would you define your items?
bro plz help!
In the inspector, as SO assets
yes
I also am doing it a bit different where I dont use scriptable objects in the game but just use them to hold the data.
Then I use the stuff set in the scriptable objects to build Items through an ItemBuilder/ Builder pattern
Not sure if thats the proper way
I've heard that generalisation/inheritance is something to avoid in Unity for the most part. Been told you can use it to extend specific classes with more functionality but the typical use of inheritance is better to just use composition since that's how the engine has been designed
That's more about MonoBehaviour scripts
This should help visualize what PraetorBlue is talking about : https://www.youtube.com/watch?v=8TIkManpEu4
Check out the Course: https://bit.ly/3i7lLtH
Not sure if you should be using composition or inheritance? Or not sure what that even means? In this video, I'll talk about the differences between the two, the positives and negatives of each, and show how to use these programming paradigms in your own game cleanly.
Unity Mastery Course...
But in general composition is better for solving a lot of problems than inheritance is
Problem is that you can't have different interactions with scriptable objects (change the Use() function for each scriptable object), So ig I won't be using that and will be sticking to classes
Haha ahh yes, well not easily at least
You would do something like mapping effect types to delegates
you can do anything with scriptableobjects that you can with plain c# classes
the benefit of SOs is being able to reuse instances
throughout the editor itself, so you can reference them on different GOs
Can you create new scriptableObjects in the Build?
sure, why not
i thought you only can through the CreateAssetMenu thing
I would recommend just using them as readonly assets though, this way you can be sure that referencing them on different GOs won't change them internally
No, you can easily create and copy them via code
Yeah I could put loads of effort into trying to find out how to make it work, and I might...
Hmmmm makes sense...
I'd rather use Scriptable Objects as it's alot easier for my Artists to use and then they won't have to keep on bullying us devs 😄
I have a question of my own.
Without giving too much context, what I think that I want is a LateFixedUpdate method, so that I can perform an action once I know all FixedUpdates have finished.
I imagine this is a common desire - is there a common answer?
(I'm not interested in specifying script execution order, unless that's unanimously the one and only correct solution)
The only real downside of SOs is asset bloat, as sometimes you don't really need to reuse those instances
but even with that downside I've came to other problems with unity's serialization with plain c# classes and it's that there's a point where these serializable classes would bloat the editor itself, or become initialized with compiler defaulted values
I don't think there is a common solution to this
That said, why would you want this?
If you want something to happen after another thing, usually you'd write an event, or have your own system that calls methods in order. Having a LateX method solves nothing
Especially when later on you need something to happen after this LateX and now you need a LateLateX
Sovles nothing? Surely it solves the issue of being able to call a method between all FixedUpdates and the end of the fixed frame?
My point is that you now have a strict limitation where something is forced to run later, so rather than having a general "Late" feature of something, instead consider hooking up an event somehow that is called after the required work is done
This is why things like LateUpdate are also bad because you will always have an order in a way and making new LateX methods for everything won't solve it cleanly
I see, thank you for the input. I'll modify my implimentation to not need one - cheers
I have a problem with my figure, no matter how i rotate it, either the parenting object nor the others below, when i walking in the simulation everything seems to be resetted. the values in the inspector are still the values like i rotated it, but the figure itself is resetted like all values are 0. i have no clue whats going on.
show your code
also !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
• Other/None
don't pm me, post it here
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonCam : MonoBehaviour
{
[Header("References")]
public Transform orientation;
public Transform player;
public Transform playerObj;
public Rigidbody rb;
public float rotationSpeed;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
//rotate orientation
Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);
orientation.forward = viewDir.normalized;
// rotate player object
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
Vector3 inputDir = orientation.forward * verticalInput + orientation.right * horizontalInput;
if (inputDir != Vector3.zero)
playerObj.forward = Vector3.Slerp(playerObj.forward, inputDir.normalized, Time.deltaTime * rotationSpeed);
}
}
!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.
use some Console.Log() messages to figure out what's going wrong
if you have a specific question, feel free to ask
the figure itself is resetted
What do you mean by "the figure"?
player character
camera rotation it seems?
does that work in unity?
i vaguely recall it not working but it's been a long time since i tried
You have all of these:
public Transform orientation;
public Transform player;
public Transform playerObj;
public Rigidbody rb;```
And it's unclear which object is which. Super confusingly named and probably duplicated objects.
Debug.Log, my bad
ive got another idea how to show you what i mean
https://hatebin.com/vgeblndado botched mercy invincibility code. the player stays invincible and can push enemies and obstacles away
what do your logs say in the console window?
collisions are still detected, but the player stays invincible
that's not what your logs would say
Logs are things like this:
Debug.Log("Invuln On");
show your console when this stuff happens
there is no "Invuln on"
then your code is never running
Is Debug.Log("Taking Damage: " + _damage); ever printing?
Sounds like isInvulnerable is starting out as true
or you're dying
those are the only possibilities
show your console
I've found the problem - the Is Invulnerable bool stays true and the coroutine stops itself when it calls for collisions between players and enemies to no longer be detected
even so it still stays invulnerable
the coroutine will stop if:
- The Gameobject running the coroutine is destroyed or deactivated
- Time.timeScale is small or 0 (will make the WaitForSeconds take forever)
- StopCoroutine or StopAllCoroutines is called
which is weird
@topaz mortar you saw my problem in the video ?
does timescale affect the Update methods?
am i right to assume that Update/LateUpdate aren't affected, but FixedUpdate is?
No
Update runs once per frame
it doens't care about Time Scale
FixedUpdate is yes
So actually I guess the answer to your whole question is yes not no lol. Didn't see the second message at first
lol, i probably shouldve written XUpdate or *Update to make it less confusing
{
int minutes = (int)(time / 60000);
int seconds = (int)((time / 1000) % 60);
int milliseconds = (int)(time % 1000);
return string.Format("{0:00}:{1:00}:{2:000}", minutes, seconds, milliseconds);
}```
could someone explain this code
Please help, it says The variable of FollowPlayer has not been asigned and then the camera dosnt follow the veichle how do i fix this, this is my code and editor
What part is confusing you
what dont you understand, looks pretty self explanatory to me
You have to assign the variable
return string.Format("{0:00}:{1:00}:{2:000}", minutes, seconds, milliseconds);
that part
didnt I
so go look up string.Format in the docs
Ohhhh thanks
you declared the variable. You didn't assign it.
!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
• Other/None
Now i declared it but the camera goes flying backwards when I press play
you can just parent the camera to the car and drag it to offset it, you dont need a script for it
Oh
I have a troubled time with enemies looking at a player. For some reason enemy looks in complete random direction, does anyone see mistake in my code? ignore layer in ray cast is so that enemy doesnt project ray in himself, its one layer only.
private void LookAtPlayer()
{
UpdatePlayerPosition();
agent.transform.forward = lastPlayerPosition.normalized;
}
private void UpdatePlayerPosition()
{
var direction = (player.position - agent.transform.position).normalized;
RaycastHit hit;
if (Physics.Raycast(agent.transform.position, direction, out hit, 100f, ~ignoreLayer))
{
Debug.DrawRay(agent.transform.position, direction);
if (hit.transform.CompareTag("Player"))
{
lastPlayerPosition = hit.transform.position;
}
}
}
i would just use the look at constraint component
rigidbody constraints?
no
please don't spoonfeed code, at least say what changed lol
Guys I need a little help.
How to stop an object from falling when this object has Character Controller component ?
so I put "before ignorelayercollision" and "after ignorelayercollision" in my code for mercy invincibility, and it does seem to stop when ignorelayercollision is called
Can you show the console
here you go
the whole console
you need to turn off Collapse so the logs are shown in order
also this isn't the full console
oh right
i'm a beginner and i wrote down the script from a video, with the things i wanted to do. but for some reason the character is rotating back in the original rotation when i start walking in the simulation. and i have no idea what causes that. and yes i know about Debug.Log messages but what exactly shall i call ? i dont even have a clue whats the matter.
Start over with the video
delete all the extra stuff that isn't in the video
follow the video exactly
and pay attention to what they're doing and try to understand it
there is nothing more in the video
I didn't say there was
You didn't follow the video
You did some things differently
so start over
and follow it more closely
Guys I need a little help.
How to stop an object from falling when this object has Character Controller component ?
:((
CharacterController only moves when you tell it to move
So it is your code doing the "falling"
the only different thing is my character, and it ignores if i rotate it. one script seems to reset it to the original position and i dont know how to fix that without ruin the meaning of the whole script. can i somehow rotate the whole pivot of an object ?
eureka
it hates layermasks, thought i could kill two birds with one stone
the only different thing is my character,
That's a pretty big difference.
There's also the high possibility that you made a mistake
I also doubt the tutorial has both of these:
public Transform player;
public Transform playerObj;```
That would be very weird
it has, but i cant tell you why.
oh yeah you're using IgnoreLayerCollision incorrectly
you passed in a LayerMask
makes sense
it wants a layer index, not a LayerMask