#💻┃code-beginner
1 messages · Page 556 of 1
i noticed one script that is able to display its variables as string, but when i do something.AsString = "abc" it actually writes it to variable how it does that?
when i do something.AsString = "abc" it actually writes it to variable
What do you mean by that? Writes what to what variable?
it has a custom class normally but its able to convert itself to string AND update itself when string is provided
i thought someone was telling me that isnt possible
You're being pretty vague but it sounds like you're just talking about a property:
i didnt knew properties can take different type
As for converting to string that's just through the ToString method: https://learn.microsoft.com/en-us/dotnet/api/system.object.tostring?view=net-9.0
Or an implicit conversion to string operator and/or the other way around
yeah i was doing once a class thats automatically spits out string, but didnt knew i can make this class with a string, and when writing to string
Without specific examples it's not really clear what you're talking about.
what do you mean by "update itself"?
oh something like this would a property yeah
w3schools, home of every student and great programming example
Too bad it's just a decade behind, making it not so useful
Though, to be fair, I guess it matches in terms of how behind Unity is in a way
I think it covers the basics very well 😅 don't discourage people from it kinda deal
Agreed, for an absolute beginner W3Schools is not a bad place to start
sorry bout the necro, but the reason why GetComponent is called "bad" is due to a common mistake that people make with it, which is calling it within Update()
since you know how Update() is called every frame
if you can set explicit references that's usually preferred
some form of singleton also works, but have to be a little careful with those too
but yea if you know getcomponent doesn't get called often then it's completely fine to use
Heya, I'm very new to unity and am trying to make Stardew Valley's Journey of the Prairie King in 3D as a learning project. I've run into a roadblock - I don't know what's the best way to make a gun system with different firing types (single fire, a shotgun/burst fire, omnidirectional fire etc.), that dynamically change from pickups. I could keep it simple and change gun prefabs that have a script attached that handles the firing, but I don't think that's the best way.
So far my research has led me to Strategy Pattern using scriptable objects, but I find using scriptable objects for this weird - you'll only have one single firing type, one burst firing type etc., so why a scriptable object?
Could anyone point me in the right direction, how I should be thinking about this, to make it easy to maintain and expand?
If a 2d collider is a trigger, detects another collider and does something, then i set the object which contains the 2d trigger collider to false then reactivate it in the same state, will it detect the other colliders and do the functions again even tho i didn't move it?
i don't wanna have my triggers always active for attacking
i tested it but it doesn't seem to work, heck only if the collider is moving is working
if my charcater stays still and attacks it doesn't deal dmg
how did you test it? Enter will probably not fire but Stay should
both stay and enter
both only work if my character is moving into the other collider
they are braindead if they don't
Are you diabling/enabling within the same FixedUpdate time frame?
ye, but the problem is that even tho is always eanbled , it doesn't detect it if i stay still
in the collider
the trigger is in another collider and it doesn't see it
try doing this.
in a coroutine
disable the collider
wait for fixedupdate
enable the collider
and see what fires
but the ontrigger stay should always detect other colliders even tho is not moving right?
yes, the question is at what point does the collider get added to the 'active' list. For normal colliders this works but I've never tried it with triggers
the problem is that now i have the trigger always active but works the same
could it be because it detects another collider i do not see?
debug your code to find out
still works the same
i really do not know what might be wrong, this is some begginer ahhh shit
when confronted with situations like this I generally make a new project and implement only the bits I need to test, this ensures there is nothing else getting in the way and masking the actually workings
simple enough to do with a couple of cubes
there was a bigger collider
i was right
but now the trigger doesn't detect solid collider
i will kms
make sure one of the colliders has a rb
rbs control physics, including collisions
i will add it rn, my savin angel
Did you not go and read the docs about collision and trigger requirements?
ofc not
too much yappin
and that's why you're getting easy-to-fix issues
Then it's no wonder you have problems, you've bought them on yourself
WRONG
If you don't read the docs, you won't ever move away from relying on other people to provide basic information
stand on their shoulders
They're there to help. If they were all one word answers no one would find them all that helpful
coding in particular is half reading
reading docs, reading errors, reading warnings, reading logs
reading examples and explanations
but all skills involve learning
and people have done hard work for you already, and condensed that knowledge
if you refuse to learn from other people, you're just going to repeat their mistakes
resources exist for a reason, use them
i got no problems reading code, just docs
Half? I would say more like 80% if not more, especially whilst learning
coding is like 90% readin code
100%. No writing involved.
no, it's 90% reading docs, 10% writing code
For the first 5 minutes, maybe*
fair
Does anyone know why it happens? i think its problem with rb
how can you possibly read code if you have never read the docs?
why what happens, exactly?
and can't really help without any info
The character gets stuck
well there's something blocking it there i guess
i just hate docs
Could something be causing it to get stuck?
yup
do you have a composite collider on the tilemap?
that's a significant problem you'll have to overcome then
and the tilemap collider is set as part of the composite?
you have not set it as part of the composite
um wdym
no i can't see because you only showed that lmao
add a composite collider and set the tilemap collider to be used by the composite
or make them audio 🙏🏻
that wouldn't really work
can't skim, can't rewind easily, can't search
add a composite collider
ok
The docs are your best friend, embrace them as such
Now the floor is falling 😂
if you added a rigidbody, make it static
hey im updating my renderer feature to unity 6 atm and im wondering what would be the equivalant to this now?
so how to get the current camera
SOLVED: var cameraData = frameData.Get<UniversalCameraData>();
Hello! Someone can tell me how to do a "setTimeout" in csharp with a cb ? I found some thing like "IEnumerator<WaitForSeconds>" but it's not working ^^
in unity, you could use coroutines
that's the path you're going towards
try googling coroutines
what do you mean by "cb" there?
Callback ^^
ah, of course. brainfarted lmao
if you want a lambda, you could use tasks?
but i'd recommend just going with coroutines, they're really flexible
Ok thank you, I'm reading how to use it 🙂
yo need some help on this
i got this slider and when i hit space at is point it just gets a random value.
a powerful website for storing and sharing text and code snippets. completely free and open source.
Coroutines have build in yield commands to wait specific times, but Unity also supports Tasks.
public async Task M()
{
await Task.Delay(1000);
// Callback here.
}
Alternative non-async Task approach which runs in the background.
public void M()
{
_ = Task.Delay(1000)
.ContinueWith((task) =>
{
// Make sure to await the task to catch exceptions.
_ = task.GetAwaiter().GetResult();
// Callback here.
});
}
Note that due to threading, you can't invoke Unity methods in here unless you run it on the main thread
Even better would be to use Unity's Awaitable pattern which has much better support and works with Unity methods: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Awaitable.html
Depending on your situation, you place the callback after the delay finishes
What is the issue exactly? You don't want hitPosition to be a random value? What should it be?
i want when i hit space hitPosition and attackSlider.value are the same but, when i do it randomly switches value
you're checking for space after MoveSlider, so it's gonna be different from the previous frame
What do you get when you log attackSlider.value before Mathf.Repeat?
MoveSlider seems to be responsible for that
Aah nice! I'll try this method too, it seems to be usefull for me later !
or some other change that isn't logged
So After is the current situation? I'm confused because it seems correct
how
Yeah i'm not seeing what's wrong there...
You tell me, is it not?
Also sdoes your slider happen to have an OnValueChanged listener?
If you're confused why the two are not the same then that's because MoveSlider adds sliderSpeed * Time.deltaTime to attackSlider.value as long as isAttacking is true
aaaa, so attackSlider.value is not gving the same value
Nop
Would love to fix the code but I don't know all the context of it
What it does etc
so there is a slider that moves to the end, when pressing space it will stop at one point aka grabbing the value it is ant and then setting a damige if it is in the correct raige
doce that make sens?
can i post videos
here?
Sure thing
can u tell me a hit position value that always gives this bug?
oh ok
wait so
wdym by %90
according to your code it goes 0 damage, then 5, 10, 5 again, then 0
but visually it looks different
and wdym it returns a float? i thought it returned damage number
mayb im just slow think im looking at smtn else
it is a slider so when i mean 90 i mean 90% of the slider is full
and i set that value so 0.9 to hitposion aka were did the player hit but for some reson form procent it changes when hitting space and then just shouts out jargin
before is in procent
the after idk
gotchu
and i dont know why this happens due to there is no point in the code where slider gets effected
it just happens when the next part is called
where do u do math with the slider
before capturing the hitposition
is this the only place
hold on
1s
i did some changes and forgot to update it
a powerful website for storing and sharing text and code snippets. completely free and open source.
was still trying to fine out why the value changes
but still no luck
this logs the same error?
so were moving slider is the math behinde the slider moving forword aka how much of the slider has moved form 0 to 1
and slider value is the same value is that aka if slider is 50% full then value is 0.5 for both
and when space is pressed it is seposto just use the last value
ye
You have "Collapse" turned on, which can cause misleading results.
This causes identical log messages to be combined together
I wouldn't expect it to happen here, though, because these numbers have a lot of decimal places
Although, I guess there's one thing to note
If you try to move a slider past its max value, it will get set to exactly its max value
using Mathf.Repeat will then give you a value of zero
i think thats what they want
So this would cause a lot of zeroes
suppose your slider is at 90%
you add 15% to it in one frame
The correct position for the slider should be 5%
i dont see how its possible that these two could give different results
ye my bad, it is not
This looks fine, yes
ye
so what i am getting at there is somthing that is changing the value to the polor poisit. so 90% to then the rest witch is 10%
sorry i am still new and some stuff fucks me over
that sounds like maxValue is 0.9, then
Also, you turned off Collapse in the console, correct?
how is the code even still going after you hit space?
it shouldnt log anything after
button
what
nope is on due to other logs form other code is on but in raw form
i don't think they are hitting space
MoveSlider also happens to log "Space Pressed at Value:"
which is misleading
so ur pressing the attack button to attack, not hitting space bar?
whats that button do
to start is button to stop is space, button just sets the value to 0 when it is called aka only reseting when the button is pressed agine
i use that to know when pressing space and to compair last value form ogin
I don't understand what the actual problem is right now
do if you hit start and hit space, it works fine. But if you then hit the button to restart, the values are wrong
slider value is logging wrong after the first attack i think
no, you just need to explain it better here
I don't get what this means
i just realized that my music was completely covering up your voice lmao
i thought the video was silent
gimme a minute
my bad
its a slider meaning one can move it form 0 to 1, 0 meaning 0% and 1 meaning 100%. sliders work in procent when askig for its value. so we say we move the slider to around 90% meaning that we have move the slider to 90 of the way
why the fuck is it see thrue
when did paint do that
XD is cool my bad for not best explaning
It’s possible the slider value only changes at the end of the cycle or something like that
im making a rhythm game that is almost exactly like this
for one, im not sure how accurate sliders are in value
discord plays videos very quietly for some reason
Can you inspect the slider? I want to make sure its max value is exactly 1
It looks like it's currently 0.9
yep 1s
how ur english is perfect but writing less than perfect
Okay, so the slider has the right max value
i got that autizum that makes writing diff to speaking
yep
It looks to me like it is wrapping around at 0.9 instead of 1.0
So you want a random value from 0-1 and it’s actually 0-0.9??
according to zion, all the values are wrong
@idle juniper can u send a vid of the bug happening
like u pressing attack
and it logs wrong
I'm looking at this example in particular.
One frame before hitting space, the value was almost 0.9
i think they hit space
so it stopped
do you guys just want the build?
they hit space at 0.9, then reset it
headache to download tho
seems like easy fix
This is the only line that actually involved hitting the spacebar
This is getting logged every frame by MoveSlider
theres one right above that..
It has nothing to do with hitting space
Everything in this example looks fine except for the fact that it wrapped around too early
Hang on a second..
Do you have two AttackSystems running at the same time here?
no
I'd expect to see more log messages (now that Collapse is off, at least), but they 're not appearing
ah, I have one other idea here
fightButton.onClick.AddListener(StartAttack);
If you have the fight button selected, hitting space will press it
That's got to be it.
This will call StartAttack, which resets the slider value to 0
Then MoveSlider runs and advances the slider a tiny bit
This gives you a bogus value
Bogus
god is that you?
thank the lord that makes sens
why does anyone use listeners? why not just use OnPointerClick?
I kind of prefer to subscribe via code
especially if I already need a button reference for some other purpose
Consider making the Fight button non-interactable during the minigame
someButton.interactable = false;
Don't let the player press the fight button a second time
this would work
You could also do nothing in StartAttack if you are already attacking
The problem is that, when you click a button, it also gets selected
this is important for keyboard/controller navigation
but, in our case, it also means that the button is now going to get pressed if we hit space or enter
THANK YOU GUYS SO MUCH!
that was a tricky "gotcha" with the UI button
if I hadn't noticed that, I'd eventually have suggested adding a few more log statements, including one in StartAttack
(to test the idea that you had a second AttackSystem somewhere)
Also, I'd tweak it slightly
float progress = slider.value + Time.deltaTime;
progress = Mathf.Repeat(progress, slider.maxValue);
slider.value = progress;
imagine the slider moves by 40% per frame and it's at 80% right now
as-is, you set the slider value to 0.8 + 0.4, which is 1.2, and that gets clamped to 1.0 (because that is the max slider value)
so after the repeat, you get 0.0
It should be 0.2 after the repeat
Saves code by not having to implement the interface tbh
Also I think onpointerdown is all mouse buttons
oh, right, asa was talking about the interface that lets you receive a UI event
that wouldn't be useful here; the AttackSystem is not the thing you click on
I was thinking about adding a persistent listener in the button's inspector
For all my buttons i just put a sprite renderer, then put an invisible image with raycast behind it
then i give it a script and do OnPointerClick with event systems
i handle all the sprite changes on hover manually and everything
gives me freedom
How’s it any different in terms of ability for that to using a delegate
whats a delegate
Like
A variable that stores a reference to a method
I guess saying delegate wasn’t completely true to how you use the system
The onclick one that is
dont u need to check that every frame? or no
like it has to be in update
instead of onclick, do function
How to downlaod manualy the recent version of visual studio in unity or how to get IDE for visual studio ?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
No?
From what you said earlier are you not somewhat familiar with events in scripting?
not very familiar with the listening thing
Delegates run whenever you invoke them. No more, no less.
i feel like we're talking about three unrelated things here
Yeah pretty unrelated just surprised they don’t know
Like I said delegate essentially is a variable for methods
Like for example you can set the delegate ‘variable’ to store a method and call it from there
// the definition of the delegate
public delegate void FooDelegate(int number);
// declaring a delegate
public FooDelegate MyFooDelegate;
public void Start()
{
MyFooDelegate = DoStuff;
}
DoStuff(int number)
{
Debug.Log(number)
}
Idk where backtick is on phone
How it relates to events is delegates can store multiple methods basically
So to ‘listen’ to the delegate you += the method you want to run to that delegate
o yea idk what this is
the delegate
ill google
wait yes i do
is delegate just an invisible word
ive never seen it
I mean you use the word itself like that yes but that’s essentially for the compiler to understand wtf ur writing and that you’re not trying to declare an actual method
ok then i really dont get it
You generally just use pre-defined types, such as System.Action
It's used to declare a delegate type.
System.Action is a zero-argument function that returns nothing, for example.
System.Func<int, float> is a one-argument function that takes an int and returns a float
Like say you have an update that needs to DoStuff() every frame, and you want to switch out what stuff it does
You could potentially call the method stored in a delegate
And change the method the delegate is storing to decide what method to run
so why not do DelegateMethod("Hello World") in this case?
because you can pass in any matching method of your choosing
because you can't pass that around as a parameter or a field somewhere
For example, I have a validation system that does this
public void Check(System.Action<string> onFail) {
if (bad) {
onFail("OH MY GOD");
}
}
very loosely
I can then do this
public void HandleFail(string message) {
Debug.Log(message);
// do other stuff
}
// ... somewhere else in my code
Check(HandleFail);
wtf
if (bad)
{
bad = false;
}
true 
Delegate types let you treat functions like any other kind of object.
my brain is halfway there i think
delegates when I want to make my code look pretty
public void Foo(float x) { return x + 1; }
public void Bar(System.Func<float> y) { return y() + 1; }
one function takes a float.
one function takes another function that returns a float
usually people recommend you to use delegates from referencing upwards, but that's too much effort. I just bi-directional reference everything
i don't understand what you mean by that
In class heirarchy I think
But it really isn’t that much effort
I don’t think it’s more effort at all actually
imagine making an inventory, your slots shouldnt have a reference to the inventory itself but a delegate to invoke from the inventory
Just a different architecture or way of thinking about communicating between classes
oh, yeah, and that's basically what the event keyword does for you
other objects can give you delegates to invoke
(but only you get to invoke them)
{
if (target == null) return;
float directionToPlayer = target.position.x - transform.position.x;
bool shouldFaceRight = directionToPlayer > 0;
if (shouldFaceRight != isFacingRight)
{
Flip();
}
}
void Flip()
{
isFacingRight = !isFacingRight;
SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();
if (spriteRenderer != null)
{
spriteRenderer.flipX = !spriteRenderer.flipX;
}
}
Someone know why the enemy is not does Flip?
Because FlipTowardsPlayer is not called or target is null or shouldFaceRight == isFacingRight or spriteRenderer == null
If you want help I suggest you start by debugging all of these
It might help you understand your code if you added some debugging into it
Alternatively, if you already did this it would help if you mention it all gets called and you confirm spriteRenderer.flipX = !spriteRenderer.flipX; is invoked
should also really do:
spriteRenderer.flipX = !isFacingRight; instead of spriteRenderer.flipX = !spriteRenderer.flipX;. otherwise you're risking them coming out of sync
hello guys
non unity question but C# related
I have <Nullable>enable</Nullable> inside my visual studio project
I can use Nullable but not NullableContext
Am i missing something here?
i shall be thankful if you can help me
Ensure you have the right using directives*
Have you read the error message?
it tells me to download the microsft.codenanalysis package
You should be using the ? notation instead of fiddling with these attributes btw
but i think there is no need for thirdparty package right?
ohk
From the docs I linked
ohk so i think i can drop this as well
are you sure its just for compilers because from what i heard its also used for nullable types and their assignment
If you need to mark a reference type as nullable then postfix it with ?, else don't
eg. string? and string
thanks let me try
Basically the compiler will transform the ? annotations into these attributes, so it can provide you with the appropriate warnings (assigning null to non-nullable type, attempts to dereference a nullable variable, etc.)
{
float directionToPlayer = target.position.x - transform.position.x;
bool shouldFaceRight = directionToPlayer > 0;
if (shouldFaceRight != isFacingRight)
{
Flip();
}
}
void Flip()
{
isFacingRight = !isFacingRight;
SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();
if (spriteRenderer != null)
{
spriteRenderer.flipX = !isFacingRight;
}
}
Like that?
This does a flip in the opposite direction
then get rid of the !
Is it possible to scroll between the Lerp value? like this?
{
float scrollValue = Mathf.Clamp(camDistance + Mouse.current.scroll.y.ReadValue() * camDistanceSpeed, 0f, 1f);
camDistance = Mathf.Lerp(minCamDistance, maxCamDistance, scrollValue);
}
Sure.
Debug scrollValue when it changes, you'll soon find out
i'm guessing it's instantly snapping to either 0 or 1
(but I can't tell, because no problem was described!)
tbh not sure
The logic doesn't really make sense
You're using the computed camDistance (which is probably not in the 0..1 range) to compute the lerp factor
Perhaps you meant to keep track of scrollValue.
not quite sure what camDistance + Mouse.current.scroll.y.ReadValue() is supposed to do
why + ?
using camDistance at all is nonsense here
correct me if i'm wrong but scroll.y is -1, 0 or 1
The magnitude depends on how you're getting scroll input
yeah, i swapped camDistance to scrollValue and works now
notably, my macbook's trackpad produces many very tiny scroll events
this causes the Shader Graph window to zoom in and out at absurd speeds, because it changes the zoom by a fixed amount
instead of respecting the strength of the scroll
pretty sure windows doesnt do that
hey, accessibility, we have to respect that
I'm guessing the new Input system has some form of normalizing the input values
you just need to respect the magnitude of the scroll event
instead of only looking at the sign
(notably, Smugliif, your code works correctly already)
thanks for the help, i haven't really done much coding in a while
It's useful to think about "units" here
cameraDistance is measured in meters, whilst scrollValue is a unitless percentage
That can help you catch errors like this
i really really wish property could hold some value is there no way to perform that
that's kinda what properties are for?
what do you mean
what are you trying to do, what problem are you having
like i would use them for many things, but 90% of time its just passing values with ifs
and thats twice as many code
what does that even mean
get if not null
simply i wanted treat it to value BUT do something under some condition
can you show an example of your intended usage
can you actually explain what you are actually trying to accomplish here? because "wanted to treat it to value" doesn't really mean anything
is
get {
Physics.Raycast(Body.position, Vector3.down, out RaycastHit hit, raycastDistance, raycastLayer.value);
return 1*(90 - hit.distance);
}
}
any different from doing this using a method with float return value?
dont tell me that isnt how most properties look like
well for starters, that isn't even how you check for null. but if the intention is to ensure it is never null or empty when getting it, then yes that is typically what you would do
and i would gladly use half of my code in properties
but you realize how many variables i would have to stick under them
why cant it have one internal one
if you want a full property then yes, you must have an explicit backing field. that is how properties work. only an auto property wouldn't require an explicit backing field because the compiler generates one for it, but you wouldn't be able to have code inside the getter/setter with that
it differs at the call/usage site, but practically no
oh ok!
c# 13 does include the new field keyword that allows usage of an auto property's compiler generated backing field though, of course that requires .net 9 so unity wouldn't be able to use that until the .net modernization is complete
- The idea is to separate full on actions and simple data access or editing
- Properties are slightly faster
You should use a property when setting data and performing functionality DIRECTLY LINKED to that data
Say… changing a text size variable; in the property you also change the text size of the linked tmpro component
If you are working with multiple different things changing loads of stuff use a method
That is the core idea
And it means when you use a property you know for sure it won’t change or affect anything else
Which leads to easier code readability and debugging if you do it correctly and everyone is on the same page
I wouldn't expect a property to be any faster. It's invoking a function
I guess it doesn't need to resolve a method group into a specific method
i am making a coundown timer and cuz the coundown goes slower when it in negatives i just changed and deleted the - is that okay to do or?
you need to fix your if statement in the Update instead
Yh just change it to 0 if it's less
by the way , you can use a coroutine for that it will be only a few lines of code. what you have rn is pretty weird.
ill cehck it out
so if it's more than 0, then subtract deltaTime twice?
think about that
yea but when ist in the negatives the coundown goes slover like seconds
Dang I didn't even see that first line lmaoo
oh
i get it i didnt even see , so thats why it goes slower thanks
Hey, I currently don't use namespaces in Unity, but Rider recommends me the following namespace because it matches my folder structure. ChatGPT on the other hand tells me that starting with _Project is a bad idea and I should use my game name instead. What's the best practice for Unity projects?
there's not really a best practice
do you want namespaces? do you have that kind of structure in mind?
like, is the folder a whole featureset, or just a grouping?
if it's just a grouping, then a namespace might not make sense
it would probably not include Scripts or Assets or anything along the path though, maybe the game name if you want it
i fixed it thanks but i have one more question how do i start this only when i press a button ? I am lost completly
did you look into coroutines 😉
it's more for code encapsualtion and also because i want to add assembly definitions later on
yes but im still a bigginer i added coroutines to my leraning list and this is my firs ever game without a tutorial
hey
I have a question
is there a way to convert a static gameobject to non static at runtime?
i really want to know about this
because whenever i go and read about it people say that marking gameobjects static is editor only
i have never accesed post peroccesing in code i asked chatgpt for some help and watched a youtube video aswell butthe vignette effect jsut stays 0 https://hastebin.skyra.pw/osavogikat.csharp
that's what the docs says indeed
when you mark it as static Unity generates a new mesh with all of the static objects, so it doesn't make much sense to undo this
you can, however, create combined meshes during runtime with StaticBatchingUtility
can it work even at build?
what do you mean?
newThing.isStatic = true;
newThing.transform.parent = transform;
StaticBatchingUtility.Combine(gameObject);```
this is how you mean it?
i want to ask does it work even when the game is built
newThing.isStatic = true;
this should be unnecessary, but yes, it will work in builds
is there something like we clone the static gameobject at runtime and delete the previous one
the new one created wont be static anymore
the static preprocessing is done in the editor or during builds, so you can't create static objects dynamically
the closest you get is the StaticBatchingUtility
or maybe doing some tricks with wrapping the GameObject in its own scene, but I'm not sure how valuable is this
is there something specific you're trying to achieve?
wait is that question to me or another guy?
the other guy, sorry
you add some logs to your code and check exactly what's going on, if the vignette value is being updated correctly
additionally, you should look into the Unity forums or even check here in the Discord search for the correct way to update the vignette – ChatGPT is not reliable and will probably give you bad information
is shader graphs a better way to make a better vigentte effect?
I think this is perfectly fine and should be easier to modify, you just need to adjust the code to do what you want
oh ok
adding your intensity without framerate independent code is bad
wait wdym
vigEffect also would throw null if thats not assigned
vigEffect.intensity.value += 0.001f; this is framerate dependent
ok so should i add timue.deltaTime
well yeah if you want it framerate independent
another reason to learn this stuff yourself insted of using a conversational chatbot
got it most of ytoutube but u right
wait will it increase if its framerate dependent
When should I use EventHandler or Action for events or anything other than those two, could I just use EventHandler for everything?
it should, but thats assuming vigEffect is not null from the previous if block
doing the tryGet everyframe might also be overkill. How many times is this thing( PostProcessVolume ) being changed anyway
not that much
does OnTriggerEnter get called in the object entering or the object that has the collider with IsTrigger ticked?
both
you can just cache the components in Start or Awake for example
ok sure
oh, for me its isn't getting called in the object for some reason? the box is ticked, the object passes through, but no call
you still need to surround this with null check just in case vigEff is null somehow
vigEff.intensity.value += 0.01f * Time.deltaTime;
also for Volume you can just assign it in the inspector, no need for GetComponent
oh ok#
I would suggest simply using Action because it's simpler
EventHandlers might be a bit more structured and will always include the sender information, but that's not always useful
performance-wise it could be worse since you're creating a new instance of EventArgs everytime you raise the event, so that's something to consider
Hello guys!
I started making a game recently.
It has a node-based movement system and I want to add a simple view bobbing effect to it.
Unfortunately I am unable to implement it.
I do the camera movement with vector3.lerp and it seems that whenever I do that it is the only thing active.
I have an actual boolean set so that whenever I am moving it should activate the headbobbing script.
I'm curous if I can make the camera headbob while learping it from waypoint to waypoint
still dont work for aome eason https://hastebin.skyra.pw/uqufevefex.csharp
you have to start putting logs to see whats happening.
also this is wrong
if (vol != null) it should be vigEff as I said a few times already
its working now?
yea
is there a way i can acces or copy a local variable to another script?
make it a public field/ prop or a method that returns it, and access across
hi i just started c# like 2 days ago. i had a command to load the next scene for my 2d game after a fade transition is complete. i have 4 objects which should be fading at the same time, however 2 of them are not fading out. i think since the fade out isnt finishing, its not allowing the next scene to load, but im not sure how to fix it. im using chatgpt to help me, by the way. https://paste.ofcode.org/sTut8u8Lwq7pDg7Lz9QvuX
This is going to start one coroutine at a time.
Each coroutine will have to complete before the next one can run
note that those are not going to fade out at the same time, since you yield each one it will fade out one at a time
however if any of them aren't fading, then that means either the coroutine stops before it reaches that point or something else is controlling whatever properties you are modifying to make it fade
ohh i see. should i just get rid of the yield returns as a whole to make them fade at the same time?
more likely one of the methods is throwing an exception which will abort the whole lot
Just calling the methods would accomplish very little
the reason i have them in the first place is because after the fade in, i wanted it to stay for about 2 more seconds. i thought this would make them wait for the 2 second pause before fading out
You could pass each one to StartCoroutine to run them separately
If they all have the same delay, I'd just do that, then wait for two seconds
I'm actually not sure what the best way to say "run all of these coroutines, then wait for them all to complete" is
but you can simplify that to "wait for two seconds"
hey guys does GameObject.Find clones a gameobject as well?
No. It finds an object.
no
i want create something that finds a gameobject and then clone it
how about this
var NewObject = Instantiate(original);```
would this clone the gameobject one time or 2 times?
once
just once
again, all that Find does is find an object
thanks for the help
it's right in the name (:
What is the use-case here?
Presumably you're finding a specific object for a specific reason
finding a gameobject in scene and changing it from static to non static
at runtime
uh oh
we're in the "Y" part of an XY problem right now, I think
explain what your original goal was
lol no
yes
i can change it to non static by this code
newThing.isStatic = true;
newThing.transform.parent = transform;
StaticBatchingUtility.Combine(gameObject);```
why is it even static in the first place if you intend to make it non-static?
i am just testing my skills tbh
how . . . ?
also developing a game that uses baked lightmaps in the form of texture that can be changed using shaders
for better computation i am just using cheap alternatives
I hope you aren't intending to run this code at runtime
EventHandler is more conventional and intellisense provides info about the delegate. The issue is EventArgs, it's a class, and you need an instance to send when invoking the event, either by using a current or new instance
Using Action gives you more control with up to 16 parameters, you can pass structs without using a class, and you can replicate an EventHandler by passing the sender as well . . .
The static flags mean nothing in the built game
yeah i know
that's why there are alternatives
i know of someone who pulled this off so i wanna do it as well
since he wont tell me
hey is there something like Scene inside unity
C#?
like calling a specific scene and then finiding gameobjects through it
hi guys, can someone help me with raycasts i cant seem to get them working. itd be best for me if i could just screenshare to you
you should definitely explain what you're trying to do, otherwise no one will be able to help you properly
no. Use Screenshots and share Code via links
just trying
what?
if only there were some sort of link that would explain what that means
Any Unity experts around who are willing to commit into looking into my problem, whatever that may turn out to be, even if it's not actually related to Unity or if someone who doesn't know anything about Unity could actually answer my question?
wow
you're not so good at reading comprehension, huh?
bro did the complete opposite of what link explains lol
Aw man I was gonna link dontasktoask then you already did it
I'm confused about what you're asking? If you have a problem, post it so people can look at it and determine if they can help or not . . .
they directly copy/pasted the what not to do part of the dont ask to ask site and just changed some stuff so it said unity
that is an interesting response, yes
write a concise description of the problem you're having. tell us what you want to achieve and what has gone wrong
hi, sorry about the confusion. Im trying to make a raycast from my player, to the mouse position in a 2D game. However, the raycast isnt working. if it collides with something, i am not getting any debug messages, and when i try to Debug.DrawRay, it isnt showing anything.
Show your code
You can use one of these paste sites to share the entire script:
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 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.
A tool for sharing your source code with the world!
sorry, i am new to this. does this work?
Can you show the entire class?
A tool for sharing your source code with the world!
i need these two images to be set as an actual image so i can place them into the script which i did. however do i need to keep the 'image' checkbox checked? because when i do, the image just turns into a solid color
okay, so FixedUpdate should be running 50 times per second. You said that you aren't seeing any lines being drawn -- make sure that you have gizmos turned on in the scene view or you won't see those, btw
One important thing is that the lines will only last for one frame
you do not have any sprite assigned to the image components, so naturally they will just be the color you've set
So you'll only actually see them if a FixedUpdate ran during your frame
I'd make the line last a bit longer to make sure that's not the issue
The fourth argument is the lifetime. You can give it something like 0.5f for half a second
Debug.DrawRay(foo, bar, baz, 0.5f);
and while we're at it, pass false for the fifth argument
This will make sure that the line can't be covered up by other objects in the scene
ah okay, ill try that. Thank your very Much!
You can also add a Debug.Log statement to the fixed update method, just to make sure it's actually running
hmm. could you explain? the way i added them to the hierarchy was by just copying the images, moving them to assets, then moving them to the hierarchy. i thought that would 'set' them as sprites. and then i added image components to both of them in the inspector window.
I don't see why it wouldn't, but if you still don't see a line, do that
the image component itself has no sprite assigned to it. are you perhaps expecting to use a SpriteRenderer to render them instead? if that is the case, why have you added an Image component?
if it helps to understand, the Image component is how you display a sprite in UI and a SpriteRenderer component is how you display a sprite in the world. use the one you need and refer to that type instead of assuming you need an Image component to reference that object
sorry im really new. i added the image component because i thought i needed to reference images, which i did in the script.
reference them using the type you are actually using
#💻┃code-beginner message
Goodmorning everyone I wish you luck with your code and 0 bugs when implementing new features
so, does the image component not allow sprites? if not, which component should i use to render sprites, and should i change the reference to the new component?
did you not read what i've said?
re-read this carefully, yes
show your code 😉
I've seen errors like this caused by a messed-up package cache
ohhh, sorry i didnt really get it
exactly. this is a code channel
then ask
a Canvas is rendered differently from things like MeshRenderers and SpriteRenderers
😂
that's why you have the Image component -- it's used by a Canvas to render a sprite
You don't put a SpriteRenderer under a Canvas -- it'll just kind of..render by itself, and the Canvas will have no clue what to do with it
They do both use sprite assets
That's what you have in your project window
Those are assets.
When you import a texture as a Sprite, the importer produces sprite assets
Both Image and SpriteRenderer can reference these assets
oh i see, tysm, it finally worked
guys i did something like this but it didnt work
if(Input.GetKeyDown(KeyCode.O))
{
GameObject gameObject = GameObject.Find("HallFurnitureMesh");
if(!GameObject.Find(gameObject.name + " Removed Restriction"))
{
GameObject NewObject = new GameObject(gameObject.name + " Removed Restriction");
NewObject.isStatic = false;
NewObject.transform.parent = gameObject.transform.parent;
NewObject.transform.localPosition = gameObject.transform.localPosition;
NewObject.transform.localRotation = gameObject.transform.localRotation;
NewObject.transform.localScale = gameObject.transform.localScale;
MeshFilter filter = NewObject.AddComponent<MeshFilter>();
filter.mesh = gameObject.GetComponent<MeshFilter>().mesh;
MeshRenderer renderer = NewObject.AddComponent<MeshRenderer>();
renderer.material = gameObject.GetComponent<MeshRenderer>().material;
MeshCollider collider = NewObject.AddComponent<MeshCollider>();
collider.sharedMesh = gameObject.GetComponent<MeshCollider>().sharedMesh;
gameObject.SetActive(false);
}
}```
any helps i can get

i am stuck
Define "doesn't work"
what do you want to happen (specifically) and what does happen (specifically)
And why not use prefabs?
i created a clone of a static mesh at runtime
the clone was also static
then i created a new gameobject and assigned its mesh values off of the static gameobject
the new gameobject was again static and this time not visible
i dont know how to make a static gameobject to non static
Might need something like this instead https://docs.unity3d.com/6000.0/Documentation/ScriptReference/GameObjectUtility.SetStaticEditorFlags.html
Not sure
Ah yeah, I saw that on isStatic, but missed it on the other
I feel like I would just use a prefab and swap the mesh, not sure
Might need to show a bit more of the code
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 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.
its the whole code
It is clearly not
It may be what you decided is relevant, but it is not the whole file
Not sure if this is the appropriate place for this question. I'm trying to figure out a way to get a nuget package into Unity, and there seems to be a lot of inconsistent information on if you should or how you should do this. Anyone know of a good guide?
using UnityEngine;
public class RestrictionRemover : MonoBehaviour
{
void Update()
{
if(Input.GetKeyDown(KeyCode.O))
{
GameObject gameObject = GameObject.Find("HallFurnitureMesh");
if(!GameObject.Find(gameObject.name + " Removed Restriction"))
{
GameObject NewObject = new GameObject(gameObject.name + " Removed Restriction");
NewObject.isStatic = false;
NewObject.transform.parent = gameObject.transform.parent;
NewObject.transform.localPosition = gameObject.transform.localPosition;
NewObject.transform.localRotation = gameObject.transform.localRotation;
NewObject.transform.localScale = gameObject.transform.localScale;
MeshFilter filter = NewObject.AddComponent<MeshFilter>();
filter.mesh = gameObject.GetComponent<MeshFilter>().mesh;
MeshRenderer renderer = NewObject.AddComponent<MeshRenderer>();
renderer.material = gameObject.GetComponent<MeshRenderer>().material;
MeshCollider collider = NewObject.AddComponent<MeshCollider>();
collider.sharedMesh = gameObject.GetComponent<MeshCollider>().sharedMesh;
gameObject.SetActive(false);
}
}
}
}```
this is the entire script now
Have you used the nugetforunity asset at all? https://github.com/GlitchEnzo/NuGetForUnity
I have never used nuget with unity before, and the concensous I see is generally not to
@summer stump I have no heard of this one, I think there is another one available in the unity asset store, but there were complaints that it was quite slow.
nuget packages are for .net and not downloaded for unity
you need to copy them from their download folder into your unity Assets/Plugin folder and assign cpu architecture to them
Did you mean to reply to the other user? Because that doesn't make sense as a reply to what I said
@snow warren just the dll?
sorry i didnt think of it
yeah just the dll
if its mono then either would work because unity compiler will code strip the dlls
also make sure the dlls are not using .net 9 because some libraries are not supported by current net version of unity 3d
if its C++ native then copy both x86 and x64 and assign architecture to them
It seems to be set to Any platform?
yea unity is intelligent enough
the problem is probably that you're getting the reference to the static baked mesh instead of the actual mesh that you want
as far as I understood you're not dealing with static game objects at all, since you're modifying them
your best option would be to uncheck static and create the batches yourself with StaticBatchingUtility
as was said before, setting the isStatic flag is irrelevant, since it's editor only
i dont know how static batch work since never worked with it before
@snow warren That appears to have worked, thanks.
lets say i am doing the static batch not from the gameobject i assigned the script to but from a gameobject that has the script but also had to give both gameobject[] as input and a static batch root
now when i give the gameobject[] to it it gives me an error
If you're using URP you may not even need to static flag stuff
just ignore it for now unless you run into optimization problems
not using urp here
ah, ok
and what is that error?
just gives System.Exception and nothing else
paste the exception here
sorry
its a System.NotSupported Exception
now i dont really know what happened wrong here
since its not being supported
Paste the full exception, with the message and the stack trace below it
ok let me
Where is a good place to store references to my scenes (they are in addressables). So my scene manager can load the scenes, maybe by type instead of strings, instead of Addressables.LoadSceneAsync("level1") ...
Should I just create an enum?

i found a cruel thing
the static batching utility combine doesnt actually combine 2 meshes
its only combines both meshes into one so that even if the position of one gameobject changes the rendered mesh stays in place
it produces a new mesh
yea
I asked earlier what's better to use EventHandler vs Action and I got most responses saying Action, so how would I refactor this code in order to replace the (this, EventArgs.Empty) to use Action ?
by string is the correct way to do it AFIK unless you do by ID or whatever it's called (don't use addressable too much), but if you need to you can make a custom property drawer that interoperates a scene type as a string in the inspector, so you're left with a scene reference in the inspector and a string reference in code.
can't you just get an AssetReference for the scene?
I don't use addressables very much, mind you
that's how I deal with scene references in my non-addressable game, yeah
while you and I are here, is there a way to require classes implementing an interface to define an event?
wait is it just public event Action<Vector2> VelocityChange;
oh it is lol nvm
since it's an interface you can also choose to omit the public, but that's it
good evening, I have a question about getting Visual Studio Code to recognize Unity keywords. Currently I followed a tutorial for a project setup tool, and after completion everything works great. Those scripts show keywords as expected. However, once I created my project folder and made scripts inside of that. Those scripts are not recognizing anything. Its confusing me as I have the new scripts and the old ones open at the same time in visual studio code. The old ones work and the new ones don't.
Both the old scripts and new scripts were opened first through unity interface
Any help is appreciated.
I think im terrible at math.
private new void FixedUpdate()
{
base.FixedUpdate();
if (longRenderer == null) return;
timePassed = (SongController.instance.instSource.time - data.pos);
if (toDisableWhenHit.activeSelf) return;
// 30 is scaling, -1 is to make the end shorter
longRenderer.size = new(longRenderer.size.x, ((data.lenght - (timePassed /4)) * 30) -1);
}
data.pos is when note supposed to be hit in seconds, when data.pos is 0 (basicaly hit when song starts) all calculations are right.
But when its bigger than 0 the timePassed goes negative and wrong...
i tried fixing this all day but i have no idea what causes it.
the calculations are for long notes when player is supposed to hit note, it stops moving and longRenderer becomes shorter over time.
What does "Create my project folder" mean?
it was just a tutorial to learn how to write a script to create a sample folder structure for your project. You enter the project name, it then creates an art folder, code folder etc.
When you create new project (except example ones) it doesnt create any folder but one for Scenes
you supposed to create them
the code in the "editor" folder is being picked up correctly in visual studio code and shows keywords
the code in the "scripts" folder is not showing unity keywords in visual studio code
chat gpt is rly good for math stuff like this, i made a rhythm game with a lot of math and i can say this
i asked it 15 times with different question formula, only thing it does is make timePassed 0 if data.pos is not 0
it basicaly breaks even more
lol
any ideas on the issue I mentioned?
It sounds like your !ide is not configured. Check the config guides below. I'd also recommend using Visual Studio(not code) as a beginner.
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
I use vs code for work so I tried that one first, thanks for the reply
just confused why scripts in one location are recognizing all the unity keywords, yet scripts in other locations don't recognize anything
Hard to say without seeing what you see.
what images can I send to help clarify?
This is an example of the working script file:
This is an example of the scripts not being recognized
Are they ever gonna get rid of the "Hold on" loading bar?
both are within the Assets folder
you can see the imports and keywords are not green and aren't recognized. Although the script does compiile and work
Quick question, my delta time is not working in the first if statement and I don't know why, it kind of just lingers around the same value. The else if works fine. I'm not sure what's up with it
Hmm... The only thing I can think of is if these 2 scripts are in different assemblies and the project files for the second script are not generated properly.
would you happen to know what action I could take from here? Or things to look up? Properly stumped on this one
erm, the whole point of if is that it stops logic... it means something is wrong with if
check if currentStamina is > 0
Wdym "doesn't work"? How are you confirming that? Use logs.
since you sau that else if runs instead every time
I see what you mean. The working file has the following:
the not working ones have this:
Maybe try regenerating project files in the external tools. And make sure the !ide is configured correctly.
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
you may want to use >= 0 instead
or <= in case if it goes negative
@open veldt
Give me one second because the error is something different
Basically the else if goes up 1 every second like it's supposed to, but the if statement doesn't go down 1 every second. Both run when they're supposed to (If runs when shifting and else if runs when not shifting)
I'm gonna screenshot the console logs
the issue is deltatime being weird I think?
wait
so when currentStamina is 0, it goes up by 1 every second until it's equal to baseStamina
Then this is what happens when I shift, it doesn't go down by 1 each second it's all just this
😭
try multiplying Time.deltaTime, and check if Time.scale is set somewhere
it affects it
alrighty
This logs show that it is going up over several frames. Probably only a fraction of a second. Are you sure you're looking at the correct logs?
It's likely that you just have high fps, so individual logs(one per frame) wouldn't show big difference.
I know it's not working because stamina should run out over 3 seconds if it were going down by one, but it doesn't, that little clip is about what EVERY printed value is because everything is around 2.99 and doesn't get lower than that
Feeling a little dumb here but i'm iterating through a textures pixels, how can I convert my index, width and height to a x,y position?
You should make your logs more verbose, because it's not even clear which of the logs this is...
This log is coming from the if statement where it checks for left shift
You can do a loop within a loop to iterate a 2d space of coordinates.
for ( x++)
for ( y++)
{
//x,y - current pixel.
// your logic
}
This is pseudocode, not real code. Just to demonstrate the logic.
Then add one in the else block and make your logs more verbose.
no no as in I have an 1d array of pixels
i don't know how to math my way into the right x/y from my index and w/h
That depends on how you made the 1d array.
nice I fixed the issue, for those that may ahve this in the future. I had both "visual studio editor" and "visual studio code editor" installed. The latter is depricated and causing conflicts. After using only one, then re-updated project preferences its working now
Texture.GetPixels()
I'm looking to get an x/y of the given pixel
it's ordered from top left to bottom right
Then it should be something like x = index % width and y = index / height assuming all variables are ints.
when you do that, it returns Array of pixels, you can calculate position by using texture size (for example, if you use texture x size in array, it will return last pixel on first row)
The best way to tackle this kind of problem is make a small example and write it down on paper. Then count and confirm.
no i can't calculate it, which is why I'm asking 😛
forsure, i have been
thanks for the help guys
you dont know math or what
tried using something similar to this and wasnt working but using your example made me realise
that i was using the wrong thing
tyvm
Next time share your attempts first. Generally spoon-feeding is not appreciated here.
It was in fact not the logs it was because I was constantly setting the variable in the if statement. Lol
Anyway fixed it
Can't see that in the shared code. I guess it was a different if statement.
No it was, It was this statement right here 😭 PSA to all Unity devs to stand up every so often and let your brain reset lmao
Ah, indeed. Missed that.
But that's not in the if statement. an if statement is just the line with the if. That's a code block executed when the condition is true, or if block.
Oh yeah, Clearly i need a nap lmaooo
im confused im using the open xr for vr stuff but i gotit working but theres these red beams shooting off the controlers as pointers i assume but i dont wantthem there any help i ca find them as an object
guys! one question, i got a simple navmesh system where it follows the player wherever it goes, however, im re-creating slenderman, how would i go about making him teleport instead of animationless walk and how would i increase his speed as the player got the pages?
I am constantly having errors with namespaces in Unity, I don't get why. I have a controller in Game.UI but it can't find it
And I import it into using
You can set the object position directly, to move it instantly.
You'll need to share the relevant errors and code.
It seems to fixed itself when I restarted vscode, I guess adding new namespaces do not update properly
what i mean is like, in the original game slenderman teleports a few inches every few seconds, and those seconds get shorter and shorter with every page collected
it doesnt teleport DIRECTLY to the player, ykwim?
Sure, just get a random position in some radius around the player.🤷♂️
saw a code in the unity docs that gives me a nice direction towards my goal, thank you though!
much love
actually, kinda wanna an opinion here
how would i make slenderman go towards the player?
using UnityEngine;
using UnityEngine.AI;
public class NavigationScript : MonoBehaviour
{
public Transform player;
private NavMeshAgent agent;
private Vector3 moveDirection = Vector3.zero;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void SlenderWalk() {
moveDirection.z = 10;
}
void Start()
{
agent = GetComponent<NavMeshAgent>();
if(PlayerMovement.numberPage == 1) {
if(PlayerMovement.playerIsAlive == true) {
print("working?");
InvokeRepeating("SlenderWalk", 3.0f, 3.0f);
}
}
}
// Update is called once per frame
void Update()
{
}
}
this code doesnt make slenderman move, so just wondering how i'd make him move before fixing this bug
What bug?
If you're using a navmesh agent, just set it's destination.
dont i have to specify it in the code? i can just do it in the inspector tab?
also, the bug is that it doesnt move at all
No. You set the destination in code. That's the basics of using a navmesh agent.
Well, you don't move it anywhere in your code, so that's not a bug.
thats what i was thinking
i was reading the docs and found MoveTowards, ill try some things and be right back!
dont spoil the answer, let me hit my head against the wall rq
Read the navmesh agent docs. Or manual. Or even a tutorial. Or even better, go through the beginner pathways on unity !learn:
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thats actually so helpful, i didnt know there was this in unity! kinda puts me on the spot but this is genuinely so nice
appreciate you man!
ill read the docs and start on this from the beginning, dont wanna get myself confused or overwhelmed
You know what I'm back cuz there's one more thing I wanna fix
I'm attempting to use the new input system and if you press W and S or A and D at the same time the character stops moving
I want to avoid it stopping because when you press the controls quickly or accidentally hit the other key the character clearly stops and I imagine it'll be kind of annoying, I just want it to keep going in the direction it originally was going if the opposite key gets pressed
I'm not sure how to make it not do that because I've been looking stuff up and cant find a thing about this problem
Is there a way to set an object to be an instantiated prefab? because using Instantiate(prefab) creates a clone of the prefab in instead of an actual prefab in the editor, and whatever I was trying to do here doesn't seem to work
Wdym? Prefabs are GameObjects by definition. You can't make a prefab of anything else. What are you trying to do?
basically...this
I mean, I guess I could just set them manually now that I think about it
This references an instance of the prefab, basically a normal gameobject in the scene. Not the prefab itself.
to maka a reference to prefab file, drag file from project view on reference slot
we don't use the InstantiatePrefab from PrefabUtility
we use Instantiate, a static function in GameObject
Instantiate(...) returns the gameobject
Hey, guys! Can you help me, please? There's an error with the script and I can't solve it in any way... 😦
I downloaded the weapon addon, but there is an error on the part of the code.:
Assets\MFPS\Scripts\Player\Controller\bl_FirstPersonController.cs(149,19): error CS1061: "MouseLook" does not contain a definition for "Init", and an available "Init" extension method could not be found that accepts the first argument of the "MouseLook" type (are you missing the using directive or an assembly link?)
Assets\MFPS\Scripts\Player\Controller\bl_FirstPersonController.cs(522.53): error CS1061: 'MouseLook' it does not contain a definition for 'SetTiltAngle' and it was not possible to find an available extension method for 'SetTiltAngle' that accepts the first argument of the 'MouseLook' type (are you missing the using directive or the assembly link?)
Assets\MFPS\Scripts\Player\Controller\bl_FirstPersonController.cs(544,19): error CS1061: 'MouseLook' it does not contain a definition for 'SetTiltAngle' and there is no available extension method for 'SetTiltAngle' that accepts the first argument.
Here code of "MouseLook": https://hastebin.com/share/tucumeduge.csharp
And the code where the error occurs: https://hastebin.com/share/derapatevo.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you can click remove embeds to save space
Did you save the code?
From a first glance it looks fine. Namespace is included, arguments seem correct
Maybe just didn't save the code?
Maybe you have two files that both contain MouseLook somehow?
What do you mean "save the code"?
"MouseLook" and "MouseLookBase"
Just wondering if you referenced te same class here
Hmm... Don't know...
If you edit your code but never saved it it will not save the new methods. Assuming you just made them.
I just downloaded the addon and the errors started at once... I've been working with this for a month.
What do you mean addon? Is it not yours?
Yes, I bought it on the unity hub.
Well I can't say what is wrong when it's an addon. It might be possible it can't even compile
Maybe try redownloading it
FWIW, it all seems fine.
Maybe you can check if it supports your version of Unity @feral moon
Note that if code doesnt compile, it could delegate down as a seperate error to different code
If I need to use gameObject.GetComponent<FetchData>() a lot in my script, should I just make a FetchData data; and
void Start()
{
data = gameObject.GetComponent<FetchData>();
}```
in the script? Is it good practice? Or should I stick to gameObject.GetComponent....
Both will work, it's just I want to keep my code clean
yes this is what you should do
alright, thanks
Awake is better practice
Roger that
guys! a question, i got a single audio listener in my game which is the camera, but everytime my character dies my console blows up with the message "There are no audio listeners in the scene. Please ensure there is always one audio listener in the scene"
how would i go about fixing this? should i even try to fix this?
i assume that for game overs i shouldnt delete my character but rather only remove its movement and add a game over screen?
or is there a better way to do it?
What I usually do is decouple the camera from the player, as in it's not on a child object. That way if I ever need to move the camera somewhere else (to make some transition for example), it's faster to edit the relevant scripts. If you have Cinemachine installed (which you should) it's even easier
whats cinemachine?
A package that makes working with cameras easier and adds way more features
Transitions, camera follows with a lot of options, coupled with the Timeline package you can make good cinematic scenes, etc.
Maybe?
not for this game in specific but it will in the future, id assume i already have to start learning it right now then
thank you guys!
guy can anyone explain why the Restart Game Button don't work when i click it, even tho i did everything right.
The button is disabled in the Hierarchy here. Do you get the Debug.Log on line 45 printed in the console?
what is it have to do with Debug.Log tho?
You placed a log that should run if the code is executed. If you do not get the log, this means the function isn't being executed
You can use that to ensure the function is executed when you click on the button
If you do not get the log, then the button isn't reacting to the click
ok let me check if the Debug pop up
god the Debug message poping up like crazy
380 of them
{
if (collision.collider.CompareTag(playerTag))
{
if (collision.relativeVelocity.y <= 0)
{
TakeDamage();
}
}
}```
Hey I'm trying to make it so that when a player hits an enemy from above it takes away their life
But for some reason it doesn't always work
and it say "GameOverScreen Show Point
UnityEngine.Debug:Log (object)
LogicScript:Update () (at Assets/script/LogicScript.cs:22)"
I know it's a problem with the collider or something.
The log you placed in the RestartLevel() method is "Player restart level", see if you get this one
nope
Then the button isn't receiving the click, make sure it is enabled and that no other object is in front of the button (that can block the click event from reaching the button)
The text is made not interactable for that purpose. Again, I can see that the button is disabled on your screenshot:
no it apper when player die
and also the button work again but it won't restart the game
Okay then it might be ScoreOverText that's covering the button
Good, you just have to make sure the "Game" scene exists and is added to your build settings
oh then i have to rename it then right?
No you need to check that you have added it to the scene list in your build settings
And that the name is correct, of course
ok kinda not understand that part, could you explain to me abit
To reduce the size of your game when you build it into an executable, you need to specify yourself which scenes to include in the game. This is done from your project settings (Edit > Project settings)
You do this: SceneManager.LoadScene("Game") - this tells Unity to load the scene called "Game". If you do not have a scene called "Game", nothing happens, or you get an error
Ohhhh i see
Your current scene is named "SampleScene", it's the default name:
If you wish to load that one, your code should say so
i fully understand now
When you build your game, Unity grabs all of the scenes listed in your build settings
It then figures out all of the assets that are used by anything in these scenes
Bro, I solved the problem, there was a conflict with the packages...
I have a new problem: Where can I ask about uninitialized objects?
That's how it decides what belongs in the built game
I'm not sure what an "uninitialized object" would be here
If you're using Unity 6, the scene build system has changed it seems, you now use build profiles:https://docs.unity3d.com/Manual/BuildSettings.html
Do you understand what I mean?
NullReferenceException: Object reference not set to an instance of an object
bl_WeaponBob.Movement () (at Assets/MFPS/Scripts/Weapon/Movement/bl_WeaponBob.cs:160)
bl_WeaponBob.OnFixedUpdate () (at Assets/MFPS/Scripts/Weapon/Movement/bl_WeaponBob.cs:100)
MFPS.Internal.bl_UpdateManager.FixedUpdate () (at Assets/MFPS/Scripts/Internal/General/bl_UpdateManager.cs:215)
Right?
Where can I ask about this? 😄
right here, perhaps!
Really? Okay...
You are trying to use a null reference on line 160 of your weapon bob script
Show us the code around line 160. Make sure to indicate that line, since we won't have line numbers
The full code or the part where the error occurred?
You can share the entire script. !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 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.
Second...
https://hastebin.com/share/widarajahe.csharp
Here my code...
that's not all 😉
For now, I want to deal with this error.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Okay, so line 160 is
tempWalkSpeed = motor.GetCurrentSpeed() * 0.06f * settings.WalkSpeedMultiplier;
Something on this line is null.
Check that both motor and settings are valid
Well, since you made it past line 158, settings is probably fine
This is an addon, and if I put it on an empty project, everything is fine, but if I put it on my own project, there are errors.
Ah, yep. That's what I mean with how it gets real fucky when it simply can't run the parent code properly. Not being able to compile, but also just not understanding the code, can lead to the program just giving weird bogus errors
Glad that works now
Check that you don't have another error earlier on
so, pause and scroll up to the very first error in the console
And before that, there were no mistakes. 😄
I'll try to duplicate the project now and delete the excess - I wonder what will happen.
rather than throwing out the entire project, you should have a look at why the error is happening
You should at least check if motor is null
throw a Debug.Log(motor) in there
Okay... I tried
Here:
if (motor == null)
{
Debug.LogError("motor is null. Ensure it is initialized in the Init() method.");
return;
}
Right?
use !code to format small code blocks or links to paste sites for large code blocks . . .
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 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.
Oops... Sorry...
That certainly works, yes
it'll tell you if motor is currently a null reference
Is this code from the asset, though?
It looks like it's reminding you to initialize the component properly
Ok, im having a serious problem Dx , im using "rigidbody.linearVelocity" to move my player, I added the camera and it all works fine, except the fact that the player movement doesnt change no matter where im looking, I am rotating my "Player" gameObject along the Y axis but still nothing, should I be using another type of thing for moving the player or did I do something wrong?
Note: The linearVelocity is a world-space property.
so rotation has no effect on it or..? How the heck do I make my character move then?
i want to set up ui in a pre known place at the end of this game i can turn it on and show (on the screen) how can i place it in a correct place? screen size is diffrent if i do scale 0.25x 1x and 5x
you'll need to modify it according to the rotation of the transform.. trying to find the right method for it, one sec
This is basically the code from the addon.
i think it should be TransformDirection, not too sure though
