#💻┃code-beginner
1 messages · Page 140 of 1
You can't convert float to bool. But where is any value of float?
well, let's check the documentation!
I saw
public static float GetAxis(string axisName);
That doesn't look like a function that returns a bool to me.
well, youre getting value, but doing nothing else
you need to check, like, GetAxis(string axisName) >= 0.1
I am trying to make fireflies randomly appear on my map at night. I took some code off the internet (see here: https://pastebin.com/pzfqGmFZ) and it does work - I was able to put a random game object in it and it spawned. However, when I put the fireflies particle system in it it does not work. I only have like three other lines effecting fireflies, by making them only appear at night in my program that manages the day/night cycle. Any ideas?
Can I use OnCollsion enter to check teh Collision between a character with CharacterController and an object with Capsule Collider? (With duckTyping)
i'm not sure how duck typing is relevant here
If you want to detect when a CharacterController tries to move into a collider, use this:
beat me to it!
This will fire when your controller tries to move into a solid collider
and what about if I want the other object to be the one that checks the collision for example
In that case, you can use OnCollisionEnter
The other object must have a non-kinematic rigidbody, and it must actually hit you
So a stationary object that you walk into won't fire OnCollisionEnter, because the character controller will never actually collide
the controller sees the obstacle and positions itself in a valid, non-overlapping position
because your code is wrong
Because you didn't implement the function correctly
did you read the error message
It's telling you exactly what's wrong
Because this message parameter has to be of type: Collision
The parameter of OnCollision and OnTrigger are different
Can you not use operators on shorts? Why's it red? It shouldn't need casting.
did you read the error message
yeah but when I put Colission as a parameter It needs a String to check the collision
and I dont want that
? Not sure what you mean, but it does not
You can do anything with collision that you can with collider
collision.collider
what
Collision is a struct
What does the error say
collision.gameObject or collision.collider
Like we said, the parameters are different, they work different. You need to read the docs
You can use operator * with shorts, but the result is going to be an int regardless. I'm not sure if the arguments are promoted to ints or if it just produces an int.
I'd have to look at the IL to know which it is
did you actually understand it, or did you just skim through the page and then give up reading it
Did you access the gameObject or collider from the struct as directed here
the documentation makes it extremely clear what you can and can't do with these types
~~I never understand unity documentation ~~
Read it more
Practice makes perfect
and if you don't understand something, ask about it
🥺
I'm trying to make a reload slider bar to show the reload progress in my 2D game. I've got it working, it's just that rather than the slider gradually increasing, it just jumps from 0 straight up to 1. I've tried to figure out how to make it work myself but I can't. Anyone have any ideas on how I could go about doing this?
A coroutine would work.
You'd increase the value by a little and then yield return null; to wait until the next frame
and you'd do that in a loop until the value reaches 1
so you have a prefab with a ParticleSystem on it, right?
and you're spawning that prefab with the ResourceGenerator component?
yes
Does the prefab work if you drag an instance of it into the scene while the game is running?
i.e. does it spawn firefly particles
if you don't try to turn them off at night, do they work correctly when spawned by the ResourceGenerator?
if so, you have a problem with that logic
Do I need to use an IEnumerator to use Coroutine?
You need a method that returns IEnumerator, yes
and then you need to pass that IEnumerator to StartCoroutine
Just tried commenting out the stop() and play() code - still didnt work. Wondering if code I stole off internet just wont work with particle systems
StartCoroutine(MyThing())
I see no reason for it to not work. I would inspect one of the instances of the prefab and make sure it actually has the particle system on it, though
Okay so I have accesed .collider.GetComponent<CharacterController> but still the collision isnt being detected, could it be problem of the CHaracterController collider then?
What does this error message mean?
wait, the placement generator script just has the fireflies prefab directly
If a method doesn't return void, it must explicitly return a value
IEnumerator is a little bit special. The compiler turns your method into a class that keeps track of what the method is doing.
Exactly what it says - you don't have any return or yield statements in it, so it's not valid yet
So you write yield return statements instead.
Is it possible to use IEnumerator and Void? Or IEnumerator must always return a value?
I think you need to read about coroutines
this has examples that line up very closely with what you're doing
Okay, thank you!
What would that even mean?
IEnumerator IS the return value
Oooh
yes, it's not some kind of special keyword
The method winds up returning the generated class
There is some compiler magic going on here. You never explicitly return an IEnumerator from the method.
which property do u change to make a game object go unactive
object.IsActive = false/true
thats whta im going to say
you need to call SetActive
activeSelf tells you whether or not the object itself is activated. It ignores parents.
whilst activeInHierarchy tells you if all of its parents are active
that's what determines if the object actually counts as being active
(both of these are read-only)
Does yield in tell Unity to wait until the next frame to execute code?
and does return null make the code return nothing?
The 'current swingable' variable is used to make the vine itself swing when the player comes into contact with it, and I need it as a 'Transform' type
yield causes an enumerator to produce a new value. The enumerator is suspended until you ask it for another value.
When Unity sees this, it waits until the next frame to ask for another value (by default)
There are certain values you can yield that make Unity behave differently
for example:
yield return new WaitForSeconds(1f);
Ahh, I see. So Yield is essentially what keeps the enumerator repeating itself?
this tells Unity to wait one second before it resumes
how do u get the gameObject's name
public IEnumerable<int> Numbers() {
yield return 1;
yield return 2;
yield return 3;
}
If you ran this through a foreach loop, you'd get...
foreach (int number in Numbers()) {
Debug.Log(number);
}
1
2
3
As for my answer to the second part, for context, this script is for the vine swinging and player jumping off it. It's based on a tutorial video I watched where it worked with an object that had ConstantForce. I'm trying to achieve a similar jumping effect but with a third person controller, which doesn't have a rigidbody as it is kinematic.
I hope this gives you enough info on my situation
foreach gets an enumerator and then repeatedly asks it for values until it runs out
why do i get this error? CS1656 Cannot assign to 'AddForce' because it is a 'method group', this is the code
Imagine that, instead of just asking over and over, you only asked once -- and then waited for a while before asking again
That's exactly what Unity is doing
because you can't assign a value to a method
did you mean to call that method?
lol
there is a plus
Is return null making the code return nothing?
yield return null makes the enumerator produce a value of null, yeah
IEnumerator is allowed to yield literally anything
and null is the most convenient way to yield something unity doesn't care about
Why do I need return null? Why couldn't I have just yield?
probably because i just stole this movement from my other game without even looking how it moves lmao
You can both yield return and yield break
yield break ends the enumerator immediately
Hence the need for yield return instead of just yield
personally, I wouldn't have minded if it was yield ... and yield break, but whatever
Methods cannot be assigned , so you cannot use =
oh nvm u had response
I see. Thank you
thanks anyway
I dunno if there's a single complete list of every kind of thing you can yield from a coroutine to get special behavior
https://docs.unity3d.com/ScriptReference/YieldInstruction.html has several of them
How to set point of rotation. I want to set point of rotation in turret
You probably have your scene view on "Center" mode
Switch it to "Pivot" mode in the top left
This won't actually change how the game works. It just changes how the scene view shows the handles
This is my code at the moment. When the player shoots, the bar goes from 1 to 0.1, but doesn't increase
not really a code question, but you need to make sure you learn how Child + Parent relationship works
also yea what Fen said about Pivot is important
The enumerator isn't repeating
this coroutine adds 0.1f to the value, yields, and then terminates
because you didn't tell it to repeat!
I have in right way but I can't set the point
if you want to do something many times, you need to use a loop
But it has yield, that makes it repeat, right?
Ooh
no, I never said that makes something repeat
wdym you can't see the point ?
I said that yield makes the enumerator produce a value and suspend itself until you ask it for another value
I see
Now, if you do that in a loop, you'll produce many values
you have to select the Move tool, gizmos first of all to see your true Pivot direction @sleek notch
and the loop will repeat every time a value is asked for
I am creating a first person car driving game. i want the camera to move and rotate according the car. how do i make the camera rotate as the car rotates.
it is rotating bad. I need where the turret is but you see
Fix the gun center in blender
You would have to find out where is the middle of that turret
you can do it in Unity as well but its harder
bruh i spent like a lot of time thinking why my movement doesnt work and then realizing that i didnt even call the movement function
It's in middle
whatever pivot you showed in unity, is not
did you make sure ur in Local Pivot mode
I don't think you set the scene view to "Pivot" mode.
Raycast2D is just overused for physics, when Collider2D.Cast generally does that smarter
i have a couple of times where I use Physics2D.Raycast, but not very many
well, it's certainly not relevant for figuring out which 2D object you're clicking on
It's also much more expensive of an operation and really only required when you need to check a shape instead of a point
where is the ray being casted from and to?
a 3D raycast goes from the camera through a point on the screen
a 2D raycast can't...do that. it's 2D
Collider2D.Cast is very similar in cost when you have simple shapes
i’ve checked by benchmarking before. I suspect a lot of the cost comes from filtering shapes based on bounds, which both have to do exactly once anyway
is there a way to check if the Item class is an inherited class? like can i see if grabbedItem is of type HeldItem which is inherits "item"?
in my testing, if you have a BoxCollider2D, using .Cast has a cost between 1 raycast and 2 raycasts
but it gives you a proper full query of that shape’s collision
yes
if(grabbedItem is HeldIem)
also, in my testing, I tested a worst case of having like 200 colliders all in a blob, where 100 of them are not relevant to the query (filtered by ContactFilter2D)
you can also store it in a variable of that type
if (foo is Bar bar)
very handy
oh cool
if (objective is SingleObjective singleObjective)
{
var display = Instantiate(displayPrefab);
display.objectiveRenderer = this;
display.Setup(singleObjective);
return display;
}
else if (objective is ProgressObjective progressObjective)
{
var display = Instantiate(progressPrefab);
display.ObjectiveEntry.objectiveRenderer = this;
display.Setup(progressObjective);
return display.ObjectiveEntry;
}
for example
the objectives are inheritance-based whilst the objective displays are 100% composition with no common parent type, hence the mild ugliness
maybe I should extract a few things out...
I've got a reload bar which I currently have following my cursor position. How can I get it so that it stays just slightly below my cursor position?
Add some value to the mouse position
How can I add a value to an objects position?
With +
Input.mousePosition is a Vector3. It doesn't let me add a value to it using +
Yes it does
I can't add a Vector3 and a float together. It's also not letting me add a Vector3 and a Vector3 together
You can't add a float to a vector3
You have to add a vector3
Why doesn't this work? I tried using Vector3.down and it worked, but I need to move it further
this is not how you create a vector3
Because that's not how you make a new vector3
why am i getting a null error when im trying to set the player script value from the held item?
how can I check if the pointer is over an UI element without using IPointerEnterHandler interface? Can it be done with raycasts for example? I'm using the interfaces, but there is one case when I need to detect in a single frame if the pointer is on the object
Hey, not sure if thats correct channel to ask. correct me if im wrong pls. I Have a script to move an object with WASD and a script to rotate the camera up and down. However rotating left and right doesnt affect the WASD movment. Both scripts are attached to the same game object so i guess its rotating, but how to i make the rotation affect the movement?
How are you moving your character inthe first place
such that are you using world direction vectors or via transform
Good news, I managed to get the jump working but it doesn't give me any forward velocity from the swing automatically. Instead it's like I'm jumping normally
You can use this to rotate your input direction from world space to local space https://docs.unity3d.com/ScriptReference/Transform.InverseTransformDirection.html
can anyone help me #archived-code-general latest question
a 2D vector made with input manager
thanks, ill look into it
ok, but still not sure what those vectors contain in gameInput.GetMovementVectorNormalized() because if you're strictly using world coordinates for movement then you're not taking in account of your transform rotation
though you've not really said why it's not working
ah ok, it's probably world then so Pumpkin's solution there is one idea
it does seem to affect the movement direction now, just not in the right way. I guess ill have to play around with it. Is there A way to start with WSAD input affecting the x and z that would be local to the game object?
works
You usually can just get the direction from the transform yourself if you are updating the rotation
transform.left / right, ect
actually, there's not transform.left
Pumkin stuff was good but I had to do transform direction instead of inversetransformdirection
so -(transform.right) ;)
thanks, ill look into it as well. It works the way it is but why not learn something new
can anyone explain to me what the singleton pattern is good for?
you need to ensure existence of something only 1 instance of it
i know someone who can explain... 
😄
are there any tools to help refactor code? I have some super tightly coupled code that I’d like to break up
good design patterns
yeah for example with AudioManager, you can emit audio from any script just by putting an AudioManager.Instance.PlayAudio() anywhere. the alternative to singletons is... dragging a reference to the AudioManager into every one of your scripts that you want to emit audio from? 🤔 oh delegates could be used for this too cant they? which would be better? wouldnt delegates be more performant actually? idk
a delagate would not repalce a singleton pattern
is just a method that runs another method when said event is invoked
A singleton is just to ensure you have exactly one instance of something. Events are something else entirely
cant said method be PlayAudio? and you invoke it from all of your scripts that need to play a certain audio
they need to be subscribed to that event though and they still a need a reference for that
unless you made the event static which then would make it a singleton (sorta)
what if the delegate is static? so you can subscribe it from anywhere?
Not if it's a static event
You can do a lot just from your IDE, not really sure what kind of tool you are expecting though.
I don’t need a tool to try to do it for me, but to maybe visualize dependencies so I can untangle them
oh there was a tool like that in asset store
it shows you all the branching in your components / dependencies
but this seems like a worse way cause just a singleton would be simpler than dealing with events and delegates, unless those are more performant than calling AudioManager.Instance all the time
i see. right now, I’m trying to split a class. is there anyway to quickly visualize which methods depend on which classes, and other functions?
Singletons aren't really a replacement for static events. You sometimes want to make sure you only have one instance of gameobject that's what singletons are for
its a design choice I think too, if you want you can use both
if an event needs to be static , it doesnt need a singleton class for it
that’s not really what singletons are for lmao
What are they for then?
singletons are so you only have one instance of a class
they don’t need any relationship to a gameobject at all
makes no difference
well they are on a gameobject, i guess thats their relationship
Exactly ^^^
Usually that one instance of a class would mean you also have 1 gameobject, the usual way to deal with duplicate instances is to destroy the duplicate gameobject
not sure it was this one
but it was similiar
https://assetstore.unity.com/packages/tools/utilities/script-dependency-visualizer-57647
only if you make it a monobehaviour, which is not a requirement
ty. i’ll give it a shot
i need some help with a bit of math
if (rotationAxis.y > 0) {
curx = cos(angletot);
curz = sin(angletot);
newx = forward->x * cosf(rotation) - forward->z * sinf(rotation);
newz = forward->x * sinf(rotation) + forward->z * cosf(rotation);
if ((angletot >= 0 && angletot <= 180) || (angletot <= 0 && angletot >= -180)) { //rotating left
if (newx > 0) {
newx *= -1;
}
}
*forward = {newx, forward->y, newz};
}
i am trying to find the new normal vector after a rotation. i am using a formula currently to find the new x and new z values but the values i get dont look correct at all?
x: -0.224394 rotation: 0.258349 total: 67.7706
x: -0.995662 rotation: 1.2513 total: 69.0219
x: -0.993595 rotation: 0.206422 total: 69.2283
x: -0.180614 rotation: 1.27595 total: 70.5042
x: -0.0545774 rotation: 0.236213 total: 70.7404
x: -0.994916 rotation: 1.61707 total: 72.3575
x: -0.990943 rotation: 0.0338062 total: 72.3913
x: -0.315979 rotation: 1.11462 total: 73.5059
x: -0.0367984 rotation: 0.284685 total: 73.7906
x: -0.929816 rotation: 1.23072 total: 75.0213
x: -0.991815 rotation: 0.24885 total: 75.2702
the x values should be changing smoothly from 0 to -1 and then back to 0 but that is not happening 🤔 not sure if i am using the equation wrong or if the equation is wrong
your agreement with this still makes no sense
because it’s just false
unity can already do this for you
i am not using unity 😆 so i have to do it this way
Quaternion.Euler(1, 2, 3) * Vector3.right produces a rotated vector
“peanut butter is a shit condiment because you have to put it with jelly”
then this isn't a unity question
Bro it does lmao. An instance of of a monobehavior would be connected to a gameobject therefore if u have one instance of a monobehavoir you have one gameobject
ik but it is game programming related so i thought some people here may know
a singleton of Component type will be related to a GameObject, yes
singletons can be of any type you want
So then why is it here
no. the monobehaviour can just stop itself from being instantiated. so you can make 20 gameobjects from a prefab with a singleton, and 19 of them would auto-destroy the singleton monobehaviour you put on them
Fen yet again proves me wrong
you are adding things to the definition of a singleton that do not exist
Singletons don't have to be MonoBehaviours. POCOs can and often are made into singletons
Right I agree singletons don't have to be tied to monobehaviours they're used outside of game development
An object being a Singleton does not provide any information, either for or against, that object being related to a GameObject
Yes it runs but somthing goes not like on PC device with the same code
Right I agree singletons don't have to be tied to monobehaviours they're used outside of game development
fixed that for you
just because you are in unity doesn’t mean you need to turn your POCO singletons into monobehaviours
They are used outside of game development 💀💀
Check what values you're getting when trying to rotate the character
Like what are you on???
loup's point is that singletons aren't tied to monobehaviours, period
not because they're used in other contexts
there is zero relationship
on PC isRot sets correctly, on mobile with the same input, etc in simulator never sets isRot true
Okay. So check what values you're getting in that function.
I agree with that statement fully
if(angle * Mathf.Deg2Rad <= deltaTime)
{
_isRotating = false;
rotating = false;
}
this is really suspicious to me
it’s just wrong, you mean
if (# in radians <= # in seconds)
you should not compare values with different units
You may be getting framerate-dependent behavior here, depending on exactly how the rest of your code works.
it was multiplied by a "sensitivity" variable earlier
is there a reason to make non-monobehaviour singletons in unity?
sure
I have lots of singleton ScriptableObjects, for example
I also have singleton plain-old classes
er, "plain old C# objects"
that's the more common name
A singleton is something of which there is only one.
That's it.
singletons are not unity exclusive
why not just make it a static class?
that IS a singleton!
ooooooohhhhhhh
by definition, there's exactly one instance
ok that makes sense
you should not mix up static classes and singletons
while technicallt true, that’s a really dangerous equivalency
most people do not consider static classes to be singletons
oh yes, I should really say a static field
I misread.
A static class is just a class that has no non-static members
there aren't any instances in the first place
I guess it kind of works as a singleton, but that's really stretching the definition
it’s just not a singleton, because there are zero instances
oh. so a static class isnt a singleton? why not use a static class then instead of a singleton class
Mathf is a static..struct, for example
It's just a way to ensure you don't accidentally put instance members in something you never intend to create instances of
static classes have a ton of downsides
I wouldn't say they have "downsides". It's just a way to have the compiler check your work.
like what?
static classes (vs singleton):
- stored on heap (instead of stack)
- No instance => hard to debug
- Keep changes to variables everywhere
- can’t be destroyed
points 1-3: what?
There IS an instance. It belongs to the type
there are several parts I’m forgetting
that’s not really an instance of the class. you can’t instantiate a static class
It is defined as an instance
Just because YOU don't instantiate it doesn't mean it is NOT instantiated
there is, indeed, a static constructor that executes before the first usage of any static members
Oh, I thought it was ON the first usage. Good to know
but i’m not sure it’s fair to call it an instance
well, those are roughly compatible (:
It is a fact...
It's just before you actually get to use it
is this spelled out somewhere in the C# spec? i'm digging around it right now
it can because it exists
C#’s docs just say it “cannot be instantiated”
the members of a static class belong to the definition of the class, and not to any instance
would not say the class IS the instance
Note: Generally speaking, it is useful to think of static members as belonging to classes and instance members as belonging to objects (instances of classes). end note
“A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for null object references. However, most…”
you know, now that I've thought about it
meaning, calls to methods in a static class are not calls to an instance
a static class is absolutely a singleton: it's the platonic ideal of a singleton, in fact
I could have sworn it was, but I can't find it.
all of its members are guaranteed to exist, and they're guaranteed to exist exactly once
because a static class has no instances by definition
it is impossible for the definition of a singleton to be violated
and therefore, a static class cannot be a singleton, which requires exactly one instance
this conversation is hilarious 😆
This whole conversation is moot.
If you could define Monobehaviours as static, you would, as you cannot you use the singleton patttern.
In normal C# if 'There can be only one' then its a static class
you can’t have 1 instance if there are zero instances to be had
of course, this is all more-or-less meaningless bikeshedding
semantics
wiki, for whatever it is worth: “In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to a singular instance”
static classes are not singletons
they are zero-tons
i don’t undersrand why this is controversial
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new operator to create a variable of the class type.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members
in other words - no instances. Just a named holder for static members
the question is whether it's a meaningful distinction
Yes because you can't put the thing into a collection. You can't call .HashCode() on it
it's literally not an object by the C# definition of objects
Hm, that is true. There's no thing there in the first place.
and that has meaningful implications
if you did MyFunction(object x) a static class could not be passed into that
you can't pass it around
also a good idea is too combine singletons with static class, implementing ServiceLocator Pattern
yeah, that's a vital difference
you can’t make a static singleton class
big benefit of singleton is controlling its instance for each scene
as static would still exist between
also I'm going to make a thread for this because I think it's clogging up the chat
As long as you're saying that the static class is the service locator for singletons that are not of static class types then sure
one distinction I forgot is that singletons allow inheritance and implementation of interfaces
oh, this issue with animation is realy bad, still can't understand why, where are differences between PC and Mobile here
later .net versions have more to static classes
have you done any debugging on the values you're computing
if you don't check your values, you're going to get nowhere
not a limitation. you can’t pass/return a static class as an argument, and you can’t hold a static class in a container
no matter how many times you tell us it's not working!
right, that is true
i'm checking it one by one but still not managed to understand where the trouble is
eg even if the language let you put an interface on a static class, you could not exploit that in any way
Log all of the relevant values or attach a debugger.
Not that I've tried to really pass singletons around or contain them but I could see some usage
i’m currently working with a collection of singletons that all implement an interface
collection of custom draw logic, where each one is a singleton, which corresponds to exactly one unique class with an ICustomDrawLogic interface.
so I can iterate through all singletons with the interface and call their interface methods
can’t do that with a static class
and the individual singletons do things like Move the start point, move the goal flag, handle text input boxes,…
yes plz
Service Locator pattern is useful for when you do want to somehow quickly access that reference without the downside of forcing that single instance constraint.
Well i tried a bit and found solution to my problem, i just put my Move and Rotate methods to Update, so only IK still staying in OnAnimatorIK and that probably works. I think the problem was that this OnAnimatorIK and Update are not synchronizing in my settings preset may be on android
OnAnimatorIK can get run multiple times in a single animation update.
that is probably what caused your problem
yes but something is different on PC and Mobile
but did you ever actually try logging anything...?
I feel like you haven't been doing anything that's been suggested to you
maybe you just haven't been showing us what you were doing, but,
looking into service locator pattern, I’m not exactly sure what the big deal is against it
it was very frustrating to watch you ask for help, say it's not working, and then just...leave again
it’s like a strategy pattern with persistent instances
nevermind, solution already works, so thanks for trying to help
basically a top layer of abstraction where a single key defines the instances
You can think of "Local Player" in multiplayer games
i don’t see the issue
or rather why there is hate
you just have a collection of an interface, and keep tabs on a “current index”. idk where the problem arises from
When you load a scene what are the things you loose exactly?
everything that was destroyed in your previous scene
every gameobject
but you can mark objects so they aren't destroyed when the scene is unloaded
DontDestroyOnLoad, right?
ye
the only thing you keep are:
- gameobjects maked dontdestroyonLoad
- scriptable objects, and other assets that are just always around
- variables in static classes
- C# objects not tied to gameobjects
basically, anything that was in the scene is lost
#4 i’m pretty sure is true as long as it isn’t only referenced by gameobject-tied objects that would be GC’d
When the scene unloads, there's a nice long GC pause
grumble
my game's loading sequence feels so good if I just never unload any scenes
just do what I do, and make your whole game in 2 scenes: main menu scene, and the everything else scene 👍
nice advice
i might make 2 more scenes tops for menus, but not much more tbh
HI boys. Is there like a shortcut like in javascript for doing something like this in c#?
healthBar != null && healthBar.SetHealth(amount);
if healthbar is not null, call the sethealth func
Well you can do exactly that
that's valid C# right there
but yes there's a shortcut
however. it is not friendly with Unity objects.
I think I know how to make the jump happen:
I gotta trick the game into thinking I'm grounded whilst on the vine collider.
Is there a way to add that in my vine script under 'OnTriggerEnter', from my ThirdPersonController code?
SO it is not recommended to use it
healthbar?.SetHealth(5);
healthBar?.SetHealth(amount);
if (healthBar != null) healthBar.SetHealth(amount);```
Well that is nice 😄
null conditional does not handle destroyed objects though so you'll run into MissingReferenceExceptions
so go with the if statement that praetor suggested
This would be the shortcut but if HealthBar is a MonoBehaviour it isn't a good idea:
healthBar?.SetHealth(amount);```
Your function returns nothing. If you want to and it with a bool it'd need to return a bool
So if an object is destroyed healthBar? would be truthy?
yes
i believe ? checks for true null
ok that's good info thx
so destroyed?.DoX()
would try to call DoX because destroyed is not null. It just == null. Then it will throw an error
this is the before and after of the load, should I use DOntDestroyOnLoad in all this objects and scripts?
The things you are referencing are getting destroyed because they're in the scene that was unloaded.
That doesn't necessarily mean that using DDOL on everything is the right choice
c# does not have a concept of "destroyed". when you destroy a UnityEngine.Object it happens on the c++ side then the overridden == operator will return true when comparing to null but the object isn't actually null until you assign null to the variable.
So using the null conditional operator and other operators that check against true null will return false when an object is destroyed but if you still try to access it you'll get a MissingReferenceException (which is one of unity's exceptions) that will basically be like "you're trying to use a destroyed object"
i’m 7 months into a project, and I have 1 gameobject with 3 monobehaviours that are do not destroy on load. And that is fine
Also script links are missing at the top, how can I preserve them
I think I can wrap my head around this. ? is built into C# and checks for real null value and == is overritten by the engine to also make the engine think it's null
It really depends what you're trying to do and what the lifecycle of all these objects is
yeah pretty much
Okay I should explain the context. It is a cannon that shoots a ball, when it reaches the target, it ends. There is a Restart button which makes a LoadScene but whenever it loads all of the links with previous scripts and GameObjects dissapear
Why is the UI manager a DDOL object but the other things aren't?
I create my game world via tiles and tilemap but in code. When I'm in editor not in play mode i dont see that world obviously. Now i know there is some unity trickery to generate the world also in editor mode - but i can't find it also don't know how its called for googling it. Can somebody guide me into the right direction please?
It isnt
Also why do you have multiple InputManagers. @ionic zephyr ?
It has to be, otherwise you wouldnt have that
out of curiosity, is it possible to tell unity to request a big block of working memory from OS, to save on allocation time? or is this already a part of unity
like if I know my game is going to be consistently using 10 MB of RAM or whatever, is there a way to articulate this so I can just ask for 10 MB of RAM, and we only try to allocate more if it isn’t enough?
[ExecuteInEditMode]
public class CreateGround : MonoBehaviour
{
....
Omg that all it took to generate the world in editor mode. Holy hell I love unity 😄
It is the before and after @wintry quarry
How do i assign a prefab to a variable in a script which is applied unto prefabs during runtime, but never exists on prefabs in the editor? Meaning i can't use [SerializeField]
just pass the reference if you can only do it at runtime
https://unity.huh.how/references/simple-dependency-injection
prefab reference needs to be serialized somewhere, and script gets reference from their, to pass on like box described
Ah ty guys
Before and after what
Okay, so it is a DDOL
The GameObject yes
the thing is I lost the references because it is referencing components of the previous scene
So we go back to where we were initially:
Why is the UI Manager a DDOL, but not the UI it manages
There is no gameObject UI Manager
Then how did you post a picture of one
it is a "Game" GameObject
When I use AddComponent<randomScript> is this creating a object of that class? Meaning I could do the dependecy injection in the constructor?
With a UIManager on it
and the "Game" gameobject has a UI Manager attached to it. making the UIManager DDOL
Making your UIManager a DDOL
Yeah, with that script
Should I make it DDOL too
yes and no, it is creating a new instance but monobehaviours cannot have constructors
More to the point: Why is the UI Manager a DDOL if it manages objects that aren't persistent
@languid spire You sound like my father, he always hits me with the "yes and no's", I see thanks
You are right, I didn´t realize that I wanted the UI to restart
so maybe the solution is making another gameObject that contains the UI Script
which isnt DDOL
I'm almost definitely considerably older than your father, but when you ask a 2 part question you get a 2 part answer
if bob.age = 87 is declared in a script, and in another script we declare string name = bob, will name.age return 87?
none of this would compile
no
That code might make sense in something like GameMaker with a big pile of global variables
and no static types
JS or TS
As someone just making the leap, that's precisely the problem tbh. 😅
I've had the opposite problem when looking at gamemaker code
"how on god's green earth do people make games this way?"
Ideally you should look at basics of c# first, before you struggle with c# syntax and learning unity api at the same time.
Strings do not have a .age field
in Unity, you're going to want to assign references in the inspector to let one component know about another component (when both are in the scene)
You don't make a ton of globals.
public class Person : MonoBehaviour {
public int age;
}
public class Car : MonoBehaviour {
[SerializeField] Person driver;
void Start() {
if (driver.age < 16) {
Debug.Log("Kids can't drive!");
Destroy(driver);
}
}
}
..that might be a little too draconian
Strings do not have a .age field
lmao
What are possible reasons why an editor script in unity is not changing the appearance of the associate script in Inspector?
- its in 'Editor' folder
- no errors in the console
- scripts recompiled correctly
- It works as expected in one project, when copied over to a new project, the same code in the same version of unity under the same folder structure path doesnt work
missing asset
do you happen to be using NaughtyAttributes in this project?
it provides a custom editor for all monobehaviours
No idea, whats that?
It's a library to add things like buttons to component inspectors
Oh in that case if its some kind of package I had to install, I dont think so
Ill check though, im not the one who set it up
I would do a search for CustomEditor
I'm not sure what happens when there are several custom editors to pick from
this shows up
ah, I mean in your code editor
I asked a couple questions surrounding this yesterday but didn't really get to dig into it, but this is exactly the kind of thing I was trying to do, but I couldn't figure out how to change driver at runtime
well, the nicest way would be to give Car a method that sets who is driving it
Like I can drag and drop whatever I want into the serialized field in the inspector, but couldn't seem to figure out how to get a different driver's age.
TMP has some, otherwise none
public void GetIn(Person driver) {
if (this.driver != null) {
GetOut(this.driver);
}
this.driver = driver;
// do anything else you need at this moment
}
if you need to see who's driving the car, you could either make the field public (which means you can't force GetIn to be used, which is lame)
or you could make a property that only tells you who's driving
public Person Driver => driver;
I will try to restart unity, thats always a candidate 🤔
or you could write a method that just returns it
public Person GetDriver() { return driver; }
hang on
the cat is clawing me
I was trying to do so in the context of instantiating a prefab.
solved. he was starving to death (food bowl not 100% full)
after restarting unity, now I get this error when I select my asset that im trying to have a custom inspector for
Like I can instantiate whatever prefab is loaded in the SerializedField in the inspector no problem, but couldn't figure out how to instantiate something else — i.e. change the prefab loaded into the serialized field in the inspector
why do you need to change that field?
why not just instantiate another field?
if (makeCar)
Instantiate(carPrefab);
else
Instantiate(bikePrefab);
Hello, I have quite an important method in one script "CalculateStats" that is private, I want to call it from another script but it does what it says on the tin and feel like making it public might give people an easy way to mess with their stats. What is the standard way of calling it from another script without making it public? subscribing to an event?
Alternatively should I even worry about just making it public?
If you need to edit it from another script it needs to be public
that's literally the definition of public
and if you are worrying about people who are modifying your game, they will likely be able to call it via reflection anyway so there's no sense in worrying about making it public just to prevent modding or whatever
Im not sure I understand, the class is public the method is private if you mean the entire script sorry I should've worded it better
private means only the script its defined in can call it
if another script needs to call it it needs to be public
Sounds like I should just make it public but for curiosities sake, Couldnt I use a workaround like subscribing to an event sent from the second script to the first and then "Event += CalculateStats;"
in terms of protecting your code, that would make no difference
sure, you absolutely can subscribe private methods to events. there is nothing stopping you from doing so. and if your architecture makes more sense to use an event for this, then do so.
but yeah, like steve said it makes no difference when it comes to "protecting" your code
No its definitely easier to just make it public I was just thinking about protecting the code
Thanks everyone for your help I appreciate it ❤️
there is one thing that you can do although it will make little or no real difference, use internal rather than public
So I have a WeaponSpawner script with a serialized field (_prefab) that I've dragged my dagger prefab into in the inspector
GameObject newDagger = Instantiate(_prefab) spawns the dagger no problem
I was considering that although funny you say that cause I just learned about internal methods 5 minutes ago looking into it, if its not gonna do me much good ill just leave it public
So then do that, but with a different prefab
i don't understand what the problem is. If you want to have multiple choices, you need multiple references.
It doesn't do much for Unity since your project is unlikely to ever be loaded as a dll in a third party program
You should either have several fields -- one for each weapon -- or should have a list of weapons
I guess that's what I was getting to. So if I have like 50 weapons, I should probably just do a list.
If you're handling all 50 in a similar manner, then yes, make a list
Thanks thats good to know
Hello, I'm trying to make it so there's seperate animations for jumping and falling, but it's not triggering the fall animation and IDK what I could possibly be doing wrong, the Debug.Log is working when it should be so IDK what the problem could be
Does anyone know any common things to look for when a public override in a subclass isn't being called even though the main class's function is being called?
make sure it is actually an overriden method and not just hiding the base class's method
the parent class's method must be virtual, and the child must override it
and, of course, the runtime type of the object must be the child class!
Yeah I'm using virtual and override. In fact, a different subclass of the same base class is working just fine - but this copy/pasted alternative subclass isn't working, despite all the code being identical. Is there somewhere I should look elsewhere?
check for errors in the console and if you are still having trouble, show the relevant code
Going back to my previous question about making a method public if I just found a way to do the same thing but allowing me to keep the method private is that something I should do or does it not make much notable difference?
Private members make your life easier.
I've been doing some refactoring of old code. Whenever I stumble into a public field, I have to shift-F12 it to find out all of the places that read it
...and that write it
in a unity project, absolutely no difference
I mean as far as I can tell this will be the only other place that intentionally calls it
Oh really so you're saying the only reason I should care about private vs public is for my own sake of keeping track of references?
yes
Ok damn that's good news for me then I was under the impression it was bad practice to make anything public unless absolutely necessary
this is specific to Unity, in the real world it's a different matter
Show the code and the calling code.
Yeah I get you probably something I should stick too for when im dealing with areas that it does matter in but just nice to know its not such a big issue in Unity. Thanks again for you help
Access modifiers get a lot more important once other people start depending on your code.
changing things that people depend on can break their code
Ohh yeah thats not something i've ever really thought about tbh
and "you from six months ago" is pretty close to another person (:
you mean like multipliers to adjust values?
Hahahh I've found that out the hard way before
i have a tendency to always add a multiplier when i use a value... multiply it by (1) even if i never use it again lol
https://hastebin.com/share/orakifuyid.csharp does anyone know why the state never changes to three??
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
the condition for the method to work is a Mouse Input
Probably because it's being set to 0, 1, or 2 every frame
Because even if it does change to 3, it will change to 0, 1 or 2 straight away
your last else if is basically an else since it's a negation of the previous else if statement
how can you apply rotational force in code? to make like an object start spinning
AddTorque if its a RB
or AddRelativeTorque
if not u gotta manipulate its rotation propertie
whats the input type for torque?
its a force..
a float.. and integer
why does this happen when i build my app?
oh right
this never happens in the unity editor
appears ur camera is spazzing out
ull have to probably share the code.. sooo many things that could be
alright
im betting the movement w/o the camera logic works
Okay, I´ve corrected it
is this fine? the if part I mean
want me to turn off the camera scripts and see if anything changes?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
it would help eliminate other causes
alright
if it works fine w/o the cam movement then you know for sure its in that code somewhere
why does the jump only work once https://paste.mod.gg/mlqvjdsdoltj/0
A tool for sharing your source code with the world!
if the problem still exists even with teh camera stuff gone.. then its something bigger
It only recognizes the Input sometimes, help
what input are you referring to?
presumabley because your collision code is never being called
Probably because you never set jumping back to false
^ im thinking the same..
This part
oh well if you aren't getting any mouse input or key presses in this class, it's likely due to the lack of actually checking any input in the class you shared
show
that Input only happens 1 frame... meaning when u press the mouse button the attackanimation goes true.. but the very next frame.. it goes back to false..
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
even if u never even release the mouse button
b/c the ifstatement only returns true the exact frame u press the mouse button..
Oh, you are right
if u want it to be continously true u probably want just the GetKey() or the mouse version
So, with that resolved, question: Why do you have a single variable that seems to be controlling like three different kinds of animations instead of actually having parameters related to the animations and proper use of state transitions?
yeah, I tryed the Attack with bool and worked right, Im just trying another way
https://gdl.space/zanidasebo.cs i am alittle lost. im trying to make my player run while holding the left shit and w key. it works if i press w and then left shift. on line 68 the direction magnitude is 0. So this is where im lost how does line 44 work?
Because that only ever runs if direction.magnitude is less than 0.1
it evaluates whether the player's input (horizontal and vertical axes) results in a movement direction that has a significant magnitude.
where are you seeing less im seeing greater than on line 44
Because the opposite of "Greater than or equal" is less than
if it's greater or equal, it runs the condition starting on line 45. Otherwise it reaches line 68 and prints 0
If it's not greater and it's not equal, it must be less
so why does line 71 not print yet line 68 does
he's saying ur leftshift doesnt run. b/c its nesting in an else statement that doesn't run at the same time ur moving
Because how would it be greater or equal to 0.1 if the condition it's in only runs if it's less than 0.1
ur condition is just twisted up
I'm not sure why you expect line 71 to run
it physically cannot be greater or equal to 0.1, you just checked that
yh my conditions are wrong just throw me off
u can put conditions Inside other conditions
instead of confusing urself with else if and else..
u can ```cs
if (direction.magnitude >= 0.1f)
{
if (Input.GetKey(KeyCode.LeftShift))
{
currentState = PlayerState.Running;
_animator.SetBool("isRunning", true);
controller.Move(moveDir.normalized * speed * runningSpeedMultiplier * Time.deltaTime);
}
else
{
currentState = PlayerState.Moving;
_animator.SetBool("isRunning", false); // Reset isRunning when not running
controller.Move(moveDir.normalized * speed * Time.deltaTime);
_animator.SetBool("isMoving", true);
}
}
u can do something like If( u have direction) inside this block do another check IF u have movement AND if u have leftshift pressed. etc
but, the more experience u have with them.. the more it makes sense on how to structure them
if, if else, if else, if else, else... etc gets nasty and hard to read lol
i think im lost. if line 44 if (direction.magnitude >= 0.1f) { and line 71 if (direction.magnitude >= 0.1f) are the same and all i have done is left shift. why does line 71 not work. yet if i let go of shift key and press W my code works inside line 44
OK thank you
u dont even need the other if.. tbh
if it isnt a magnitude greater then it has to be a magnitude lower
Do you know what else means
yes if first condition is not meet else will always run
So, if (direction.magnitude >= 0.1f) is your condition on line 44.
When does that not run
yup, so if ur not moving.,. the else in ur case runs.. which is where u also check for leftshift..
What conditions must be true for this if statement to never execute
that doesnt make any sense lol.. if ur not moving.. why even bother checking if shift is pressed?
not like ur gonna sprint while idling
it will be idle
ya, no reason to have ur leftshift check WHILE ur idle.
https://gdl.space/fufehecohu.cs here i moved some stuff around.. i think it makes more senes like this.. study it and compare.. and u tell me
If you are specifically only running this block of code when the magnitude is less than 0.1, why would you expect an if statement checking if it's greater than 0.1 to ever execute
thanks you
just wanted to make the state change back
actually it'd look more like this..
to idle
the orange block all would be running if ur moving
the else statement would be if ur not moving..
How would the magnitude be >= 0.1f if this is code is inside the else block of something that checks if it's >= 0.1f
You're checking "If this thing is less than 0.1 and also greater than 0.1" which makes no sense
please delete this and try again !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.
yes thanks but i dont want to be walking before im running i want to jump straight to running from idle if im holding left shift first. I think ill need to add another animator transition though
the code part of it anyway.. no ones gonnna read that code like that 😦
ya, thats why i was saying.. in that first if block (you know ur moving) then u can do another check INSIDE the first if.. to tell if u should be walking normally or sprinting (left shift being pressed)
but in the else statement is if ur not moving.. it doesnt matter if ur left shift is pressed in that case
ONLY if ur moving (THE FIRST IF)
i understand many thanks
hello, im trying to make a vampire survivors type game and rn im trying to set it up so whenever the player moves out of a loaded chunk it loads another chunk, but for some reson i keep getting this error whenever i move my character
this is the code thats currently giving me issues:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapController : MonoBehaviour
{
public List<GameObject> terrainChunks;
public GameObject player;
public float checkerRadius;
Vector3 noTerrainPosition;
public LayerMask terrainMask;
PlayerMovement pm;
// Start is called before the first frame update
void Start()
{
pm = FindObjectOfType<PlayerMovement>();
}
// Update is called once per frame
void Update()
{
ChunkChecker();
}
void ChunkChecker()
{
if (pm.moveDir.x > 0 && pm.moveDir.y == 0) //right
{
if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(20, 0, 0), checkerRadius, terrainMask))
{
noTerrainPosition = player.transform.position + new Vector3(20, 0, 0);
SpawnChunk();
}
}
else if (pm.moveDir.x < 0 && pm.moveDir.y == 0) //left
{
if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(-20, 0, 0), checkerRadius, terrainMask))
{
noTerrainPosition = player.transform.position + new Vector3(-20, 0, 0);
SpawnChunk();
}
}
else if (pm.moveDir.x == 0 && pm.moveDir.y > 0) //up
{
if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(0, 20, 0), checkerRadius, terrainMask))
{
noTerrainPosition = player.transform.position + new Vector3(0, 20, 0);
SpawnChunk();
}
}
else if (pm.moveDir.x == 0 && pm.moveDir.y < 0) //down
{
if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(0, -20, 0), checkerRadius, terrainMask))
{
noTerrainPosition = player.transform.position + new Vector3(0, -20, 0);
SpawnChunk();
}
}
else if (pm.moveDir.x > 0 && pm.moveDir.y > 0) //right up
{
if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(20, 20, 0), checkerRadius, terrainMask))
{
noTerrainPosition = player.transform.position + new Vector3(20, 20, 0);
SpawnChunk();
}
}
else if (pm.moveDir.x > 0 && pm.moveDir.y < 0) //right down
{
if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(20, -20, 0), checkerRadius, terrainMask))
{
noTerrainPosition = player.transform.position + new Vector3(20, -20, 0);
SpawnChunk();
}
}
else if (pm.moveDir.x < 0 && pm.moveDir.y > 0) //left up
{
if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(-20, 20, 0), checkerRadius, terrainMask))
{
noTerrainPosition = player.transform.position + new Vector3(-20, 20, 0);
SpawnChunk();
}
}
else if (pm.moveDir.x < 0 && pm.moveDir.y < 0) //left down
{
if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(-20, -20, 0), checkerRadius, terrainMask))
{
noTerrainPosition = player.transform.position + new Vector3(-20, -20, 0);
SpawnChunk();
}
}
}
void SpawnChunk()
{
int rand = UnityEngine.Random.Range(0, terrainChunks.Count);
Instantiate(terrainChunks[rand], noTerrainPosition, Quaternion.identity);
}
}
this is the error
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Im sure in games if you hold a button and walk you run. I thought that maybe you could go straight into run. Would you say always walk first?
lol, thats a bit better
my animator is set up like so
So i would have to add another tranisiton. but im not sure if i should stick to this and walk first frame or go straight to run
this error means ur trying to access an element of ur list or array thats not there.. the array starts at 0 and goes up, 0, 1,2,3,4,5 etc... and stops at its last element..
eitehr ur trying to access a negative number of that list.. or an index thats ABOVE the amount of elements in the list
Seems like terrainChunks is empty, if that Random.Range is out of bounds. Try logging rand and the Count of the terrainChunks list
but like he said ^ if its empty even a 0 will be out of bounds
u would check immediately. if u know theres input
so.. i set it to Walk speed. and then run an if() check to see if the left shift is pressed if it is i change it to my run speed
Thank you.
then after all that it uses w/e i chose for that value and just passes it into my Move() function
many thanks spawn and digiholic
no problem, remember code runs from top down lol (in a code block)
so u can do all ur checks and set up ur variables then at the very end u can use those values
this is how i got it set up in the engine, theres already 1 chunk in place
Log it anyway
how do i log them? been a while since ive tried that
well with this collapsed its ur word that theres a Chunk in there
danm cant use gifs
foreach (int item in myList)
{
// Do something with each item in the list
Debug.Log(item);
}```
yeah i feel stupid now
Just logging the count is fine
its either because im getting tired of looking at unity all day or something else cuz i did not see that colapsed part
lol
we don't need to know what is in it, just how much
could be both /shrug
dude i forgor c# syntax
an extra set of eyes is a common fix for coding..
Then look it up
thats why theres the RubberDuck debugging folklore
yeah that part was empty
just talking it out and looking over things uve already looked over can instantly pop up new information
lol
👍 sounds like that was the issue hehe
now it loads a chunk but this happens
google is stupid and my questions are too specific for it to bring answers
progress
lemme try for a bit actually
that error tells u exactly how to fix it tho
Then it's likely not a syntax issue
wait wait i am looking it up
There's no way you're running into a syntax error that has never been encountered before
I may be stupid, but I'm stumped on getting a boat to rock back and forth.
I thought it'd be pretty simple: Boat.transform.Rotate(0,Mathf.Sin(Time.time),0);, which does, in fact, look very nice - but it only rocks it to the right, of course, because sine goes negative only enough to return it to its original position.
I really am struggling to figure out a simple way to make it rock to the left, too.
they are assigned tho, i just checked
oh wait they aint, wtf, i could have sworn i assigned them earlier
computers usually dont tell lies 😉
could try pingpong time
transform.Rotate adds rotation, it doesn't set rotation. You give it an amount to rotate by. So, you start at 0, add a little bit at a time until the Sin hits 1 and then back to 0, then you subtract that exact amount back, putting you back at 0
i am trying to make a struct with 2 vector3 in it
ig i missed those
Because you never assigned a value to FirstPoint
i have that same mechanic. let me see if i can find my project
does assigning its value in a switch not count?
What happens if DoorsDirection is 0, or 5?
What is FirstPoint then?
What data structure is DoorsDirection that can only hold the values 1, 2, 3, and 4?
its int and when its assigned it will always be from 1 to 4
like east west north south
Yeah pretty sure int has more possible values than those four
how do you make a 4 value data type?
Enum
oh yeah enum i havent ever used it
You can't. That's how I knew you didn't have one
public enum Direction
{
North,
South,
West,
East
}```
thx
but that would mean changing alot of ur code
Even Enums are just ints, it will only produce a runtime error when you try to cast it, it'll happily let you do (Direction) 5 in a case block
progress
ahh true true
nah its eaey
a lot easier to read and work with tho 👍
So you'd still need a default case to assign a value to any local variables in the switch
i have only been writing since today
But yes definitely use Enums over magic numbers
yeah thats so helpful to know
Mhm. That's what I concluded, but my inital experiments with setting transform.rotation directly were stumped because I don't know fuckall about messing with quaternarions, sadly. Guess now's the time to fiind out, because I can't seem to set transform.rotation.x individually.
transform.rotation is a Quaternion. You're not gonna want to touch any individual components of that. Try setting transform.eulerAngles to a Vector3 instead
you can copy ur rotation value into a variable
edit that variable and put it back in
// Get the current rotation
Quaternion currentRotation = transform.rotation;
// Modify the X component of the rotation
Quaternion newRotation = Quaternion.Euler(150f, currentRotation.eulerAngles.y, currentRotation.eulerAngles.z);
// Apply the modified rotation to the object
transform.rotation = newRotation;```
something like that.. but theres even a shorter way to do it i cant think of rn
transform.eulerAngles = new Vector3(...)
aye! lmao thats it ^
does unity recompile unchanged codes?
coffee is jetlagged
like redo everything when you reload the editor
Yes, whenever anything in an assembly changes, it has to recompile the whole assembly. That's why for large projects Assembly Definitions are recommended
i see
At the very least to separate out any included assets from your own code
i should restudy how to set up assemblies
tried it before, just feel too much work setting it up
does that package manager automatically separate your installed packages?
how do you get a randomised enum?
Many packages already come with them, you'd just need to create a separate one for your code and reference them. Otherwise, just drop an asmdef in the asset's folder.
public static T RandomEnum<T>() where T : struct, IComparable, IFormattable, IConvertible =>
((T[])Enum.GetValues(typeof(T))).GetRandomFromList();
```I had this
that's quite the piece
You can cast an integer into an enum, so for the enum example provided above, you'd generate a random value between 1 and 5 (remember the end point is excluded for ints) and then cast it to your enum
(Direction) Random.Range(1,5)
took my like 20 mins and 7 other peeps helping to make it like that
(Assuming you've explicitly changed the numbers in your enum to 1,2,3,4 instead of the default 0,1,2,3)
i cant test my code i have to trust the code for now
public static T GetRandomFromList<T>(this IList<T> list)
{
return list[UnityEngine.Random.Range(0, list.Count)];
}```this is the other method btw
how am i supposed to know that, i just did this
Actually not that bad idea to getvalues then randomize it
so in this case it doesnt matter if you label them
or what for that matter
You're able to assign any number to it, so you could do X=1, Y=2, etc.
Since you did not, they're in order. X is 0, Y is 1, and so on
yea, it took 7 peeps and 20 mins to figure out the most efficient way to do this job
So (Direction) Random.Range(0,4)
ok i see
lemme fix thazt
just so you can lazily do ```cs
Direction.RandomEnum()
thx so much
The standard sine function oscillates between -1 and 1, and if you only use Mathf.Sin(Time.time), it will oscillate between 0 and 1, causing the rotation to only go in one direction.
To make the rotation go in both directions, you need to multiply the sine result by a larger value to increase the range and introduce negative values.
cheers for your help i changed them to triggers and tidy the code up. Now transitions between all 3 states.
if (hitInfo.collider.TryGetComponent(out IDamageable dmg))
{
dmg.Damage(hitInfo.point); // Null Reference error?
}
How can this line give Null Reference ?
I am Hitting the if statement, how can it be null?
If the IDamageable component is attached to the game object but is not initialized (set to an actual instance), then calling dmg.Damage(hitInfo.point) would result in a NullReferenceException.
IDamageable is an interface
if (dmg != null)
{
dmg.Damage(hitInfo.point);
}
else
{
Debug.Log("IDamageable component found but instance is null!");
}```
try that and see if it debugs the log
I'm trying to use the Video Player component to play videos on an object. I can't seem to figure out how to change the video file at runtime, if possible at all. Anyone any leads?
the inspector should show a slot for the video file..
u just grab a reference to that VideoPlayer and set the file
Oh nvm the error is something else but Unity was being stupid
I dragged and dropped another video file into the inspector field at runtime, not via code
I'll try via code next
Double click was taking me to that line , It would make no sense since interface cannot be null , it was implemented especially if it hit that if statement TryGet
its VideoPlayerComponent.VideoClip
Odd. Even if I do Boat.transform.eulerAngles.Set(100, Boat.transform.eulerAngles.y, Boat.transform.eulerAngles.z);, I see no change to the X component.
lol, ole "Unity being stupid"
This was my error 😦
var dir = limbInfo.hitPoint- Camera.main.transform.position;
hate when Unity decides to be stupid on me like that lol
My Camera was deleted
Just curious, how do you damage with Vector3? Because hitInfo.point returns a world space Vector3
ya, that error was OFF by a mile then
I pass the direction of my damage to whoever receives it to do something with
Player Damaged by Vector3.up
Oh okay then
you may even have to Stop it and then change the clip and restart it
but i dont see those functions on it .. so just test it out and see lol
Directional Knock-back
big knock
Oh it seems this was actually sufficient haha
vp.clip = replaceVideo;
thanks mate
np 👍
Doing this:
// Modify the X component of the rotation
Quaternion newRotation = Quaternion.Euler(currentRotation.eulerAngles.x, Mathf.Sin(Time.time), currentRotation.eulerAngles.z);
// Apply the modified rotation to the object
Boat.transform.rotation = newRotation;```
the boat uh, spins in circles.
not ideal!
Yes that is indeed what I did.
Surprised you don't recognize your own code!
But yes - putting it on the X component causes strange vertical rocking, the Y component causes it to rotate around the Z axis, and the Z component causes some weirdness.
2D game?
3D.
b/c it doesnt look the same
i have timeElapsed * rotationSpeed
u ahve none of that.. just Time.time like u did last time
And what should boat do?
Just a light rock side - to - side across its X axis to simulate gentle waves. Here's my original post on the matter
https://gdl.space/femibiquwa.cpp <---- CODE again..
// YOUR CODE
Quaternion currentRotation = Boat.transform.rotation;
// Modify the X component of the rotation
Quaternion newRotation = Quaternion.Euler(currentRotation.eulerAngles.x, Mathf.Sin(Time.time), currentRotation.eulerAngles.z);
// Apply the modified rotation to the object
Boat.transform.rotation = newRotation;``` is not my code..
it doesn't
- set a start time
- doesn't update the elapsed time
- doesn't use either of those in the rotation modification
- doesn't construct the angle variable with a Speed Modifier
why do you use extra vars if you can use Time.realtimeSinceStartup
im a Var junkie..
i just prototype code for the most part.
i'll delete this before days over
but ya, i didn't even know about that property tbh
most uncanny
yeah, it should be around y axis, not z
it is
thats rotating on teh Z axis btw
got to use local Rotation
b/c ur boat is all flipped upside down n shit
if it matched the world coords it would work
transform.localRotation
the way the modeller exported it.
The modeller is me
u can use a parent container and orientate it correctly
and just use the ship as a child of it (rotated to match the way it should face)
and put the code on the parent instead
oh never mind. We got it
good evening, guys Can i ask a question?
That is a really stupid solution and I don't like it but I'll keep it in mind
sure
pendulum...
i just installed unity 2019.4 and it is not opening on windows 7 What should i do?
first off restart your PC and try it again
Oh, and since this always trips me up: how can I make this rotation work frame-independently?
it'll save u alot of heartache if it boots up
you can use time.DeltaTime
multiply it with the rotationSpeed multiplier
do it in fixedupdate
if its running in fixedupdate then its already frame independent
yea it does
fixedupdate runs at a fixed rate
doesnt change at all
doesnt matter if ur running 5fps or 340fps
fixed timestep.. is a constant
🫡
stock settings are 50 frames/second
on the physics (FixedUpdate)
lower the number the faster the calculations
why dosent the sword activate itself https://paste.mod.gg/djfzsycqspmq/0
A tool for sharing your source code with the world!
do you have "e" set up as an input?
update doesnr run when it's inactive
but he's activating some other object i believe
NailBehiviour should be active
for the code to work
ah, right, so question would be is if the log is printing
