#💻┃code-beginner
1 messages · Page 247 of 1
it destroys other instance if it exists
read what I wrote
I mean maybe you shoudl read the code once again? 😄 Because what the code tells makes perfect sense to me
what your code should be
void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
well yeah... okay, that looks better 🙂
I will be quite honest: this piece of code is how I saw it in one tutorial. it worked and well, made no trouble so I assumed it's liek it should be
I need help on parsing a Json array string:
Assuming this is the string I get in a SendMessage pointed from a Front End to a Unity WebGL instance
string jsonString = "[{\"title\":\"Be Effective\",\"desc\":\"\",\"name\":\"general_be_effective\",\"isCompleted\":true},{\"title\":\"Be Proactive\",\"desc\":\"3000 points\",\"name\":\"be_proactive\",\"isCompleted\":false},{\"title\":\"The End in mind\",\"desc\":\"6000 points\",\"name\":\"begin_with_the_end_in_mind\",\"isCompleted\":false},{\"title\":\"Put First Things First\",\"desc\":\"9000 points\",\"name\":\"put_first_things_first\",\"isCompleted\":false},{\"title\":\"Think Win / Win\",\"desc\":\"12000 points\",\"name\":\"think_win_win\",\"isCompleted\":false}]";
I've prepared this class to fill up with all the values stores in the json
public class TrophyData
{
public string title;
public string desc;
public string name;
public bool isCompleted;
}```
Now I usually just had a simple method like this one to parse
```public void SetDataTrophies(string jsonString)
{
TrophyData[] trophyDataArray = JsonUtility.FromJson<TrophyData[]>(jsonString);
//LOG
foreach (TrophyData data in trophyDataArray)
{
Debug.Log("Title: " + data.title);
Debug.Log("Description: " + data.desc);
Debug.Log("Name: " + data.name);
Debug.Log("Is Completed: " + data.isCompleted);
}
}```
But for some reason i now get an error on the JsonUtility.FromJson part
"ArgumentException: Return type must represent an object type. Received an array"
Can somebody help me figure out whats wrong?
As it says, JsonUtility can't deserialize arrays as the root element
Cant newtonsoft do it?
Any proper JSON library can
how to make a button where when we press it our player will do an animation with an example of a cooking animation, and it will be triggered by one button
{animator.Play("nameofanimation");
}
that should work
but thats a very hack way to do it. ud want much more than that
So should I integrate something?
It would probably be a good idea in general to start using something else other than JsonUtility to read and write JSON, yes
I think the way you did it was actually in the official Unity Learn pathway. But you left out the static reference to the Instance
How bout sharing the one that doesn't work and the actual error message you see?
I guess I was tired or stupod last time I trìed doing this. I tried it once again like 40 min ago and it worked just fine. I believe it was giving errors because 2 "singletons" were attached to a single gameObject
Wouldn't be a problem
what's that? can i know?
ah, i may not be able to help u ther
is there any way to check which key is being pressed? something like Input.getKeyPressed(), im looking for it but i dont find it
Anyways, problem is gone but thanks to posting that code, well, now also my gamemanager got a bit better code 🙂
Either iterate through all keycodes or use https://docs.unity3d.com/ScriptReference/Input-inputString.html
Or switch to the new input system which has slightly better support for this
new input system
oh lit that? xD
are there some libraries I can include? Sorry but I have really poor knowledge about this topic
The one Unity released 5-6 years ago
Newtonsoft
Do someone know how I can make this change the text to the current number of the countdown? The countdown starts at 3 and I want it to show 3 then 2 then 1
i guess you would use count.ToString() rather than countDownTime as you are not changing that in the while loop
I will try
Vector3 targetPosition;
Vector3 velocity = Vector3.zero;
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, duration); ```
!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.
Also, feels like something's missing
Here, use it wisely: `
alright thanks
And where do you run it from?
in update
Is velocity a local variable?
global
Should be working then.
i mean it is working
I mean frame independent.
its just that on lower fps its faster
yeah thats not working
It should be transitioning from source to target position in duration time.
i can send u a video once i get on my pc of what it looks like
!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.
Is there a clean way to detect when someone clicks outside of UI?
I'd like to make my ui close if someone clicks outside of it, some people suggest a larger image but that's not clean and wont work for world space ui
Make a Screen Space - Camera Canvas.
Set the canvas Plane Distance to ~500 or 1000
Put an Image component on it and set the alpha to 0, with the full stretch anchor preset so it covers the whole screen.
Put an EventTrigger with a PointerClick event on it (or a custom script with IPointerClickHandler)
Whenever you receive the pointer click event on this thing, it means the player clicked outside of all other UI.
alright im on my pc
give me a 2 minutes and i'll send u the video
can you see when im in full screen and the fps is like 600 its a lot slower?
and its faster when im at 100 fps in windowed
Is it possible to create an animation that follows the cursor? Like the one on this video https://www.youtube.com/watch?v=DPqc7qYDtzM but not just modifying the Z rotation but rather completely triggering a different animation when mouse points somewhere else? Like say a 2.5d game, project zomboid sort of mechanic but the sprite is 2d
In this video we will learn how to Aim a Melee Weapon at mouse pointer in Unity 2D. In the later video I will show you how to perform an attack and how to create enemies to fight with.
Make a Juicy 2d Shooter course:
https://courses.sunnyvalleystudio.com/p/make-a-juicy-2d-shooter-prototype-in-unity-2020
How to get input using the new input sys...
It looks like it's a bit more complex than just smooth dumping the position. Share the whole code.
sure give me a second
How can I integrate it? I dont have a reference to that lib
i have to warn u its quite long, but your looking at line 23/27, line 86/96, line 107
https://hastebin.skyra.pw/velemezowi.pgsql
maybe its because i use same velocity for every smoothdamp?
but i dont that should be a problem since their not playing at the same time
Found something like this, and modified it a bit
public class CloseOnClickOutside : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {
[SerializeField] private ScriptableObject toggleableUI;
private bool _inContext = true;
private ToggleableUI _toggleableUI;
private void Awake() {
_toggleableUI = GetComponent<ToggleableUI>();
}
void Update() {
if (Input.GetMouseButtonDown(0) && !_inContext) {
_toggleableUI.Hide();
}
}
public void OnPointerEnter(PointerEventData eventData) {
_inContext = true;
}
public void OnPointerExit(PointerEventData eventData) {
if (!_toggleableUI.IsVisible()) return;
_inContext = false;
}
}```
Downside, I still gotta figure out what's wrong with it cause once the menu closes, it'll never open again, but if I can make it works it seems to be a bit less setup?
Hmm... Where do you set ladderStartPositionDuration?
editor
they are never changed
when playing
Can you debug ladderPositionVelocity and see if it's different between windowd and full screen?
sure
And debug the duration as well, while you're at it.
yes
the one on the left is with lower fps
im not sure if this is what you meant
but wont the velocity also be different depending on how far im away from the target position?
ladderStartPositionDuration is always the same
Yes. It should.
Hmm... The velocity seems to be quite different though. Although I guess it's showing the change per frame..?🤔
yeah
let me try simulating this on my end
I'm trying to make a list in Unity which only has integers, but those integers skip some numbers, e.g 1, 2, 3, 4, 6, 7, 8, 10 instead of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Unity keeps giving me the error:
Here's my code:
Arrays in C# have Length, not Count
also this code isn't going to give you what you want 😛
Thanks, also nice to meet you again 😄
Basically defining lst here
I would do something like this:
int[] GenerateNumbers(int count) {
int numbers = new int[count];
int numberOfNumbersGenerated = 0;
float chanceToSkip = 0.3f; // 30% chance to skip
for (int i = 0; numberOfNumbersGenerated < count; i++) {
if (Random.value < chanceToSkip) continue; // randomly skip numbers
numbers[numberOfNumbersGenerated] = i;
}
return numbers;
}```
ok, that's nice - again arrays use Length, not Count
int[] means array of integers
where does it even have count in that one
I'm trying to make a list in Unity which
The only thing I see throwing red flags relative to delta time would be cs float ySmoothVelocity = Mathf.Lerp(rb.velocity.y, yTargetVelocity, 1 - Mathf.Pow(ladderAcceleration, Time.deltaTime * 10));where the exponential arithmetic may yield vastly different results
thats the correct way of doing it
Just did a quick test, and it works the same at different frame rates
But I've no clue how your code actually operates
bro what
my unity is tweaking
Hi guys, I made save and load script yesterday and today I changed my time on laptop cause it didnt showed it correctly and now in my game my save and load system doesnt work(more specificlly only load system, i can save but not load) and it shows this error:
you shouldn't really be writing your save game file to the Assets folder.
It should go to Application.persistentDataPath
Delta time in smaller rates or larger rates will play a huge difference on that line.
getting an error with my random object. any idea why this is?
using Random = Unity.Mathematics.Random;
public class PatientSpawner : MonoBehaviour
{
private LevelManager _levelManager;
public bool playerSpawned;
public GameObject patient;
private Random random;
void Start()
{
_levelManager = FindObjectOfType<LevelManager>();
random = new Random();
}
open the full stack trace
float spawnTime = random.NextFloat(1f,2f);
oh okay, where would that save my data
I think smoothDamp is working fine.
These dots were created by damping from [0,0,0] to [1,0,0] with a smoothTime of 0.2f
I used deltaTime values of 0.001, 0.01, and 0.1 (bottom to top)
i dont understand the issue, ive initialised a new object
This code is resaonable
so what could my issue be?
oh weird, i thought it did that automatically
It gives you a framerate-independent lerp with a moving start point
Not the Unity Mathematics one. System.Random does.l
u can clearly see that its running faster at lower frame rate right?
its not just me
anyway i'll be right back if anyone knows what the issue might be please let me know
Right, so notice that the blue line is significantly lower at 0.05 seconds compared to the others
If duration of the animation is important I don't think SmoothDamp is going to guarantee it.
What is your stopping condition?
That's something I forgot to bring up last night.
it works now, but each instance of this object has the same seed now so every value is the same between these 4 objects
well, yeah, because that's 10 frames per second
give them different seeds then. Use an instance id of an object or something
Stop showing images without posting a valid argument. The results will be the same, how they get there will vastly differ
Uncertain if it's your issue but it's the only thing relative to time that would stand out immediately with what you've shown
maybe
the page explains the point of calculating the t factor like that
when the coroutine finishes
thats when the smoothdamp finishes
i'm using GetInstanceID, but the random values seem to be very close to each other. any idea why this might be?
this could just be random luck
as long as the seeds are even slightly different, the results should be very different
I'd try to isolate that smoothdamping from all the other logic and see if that works. In my tests, there doesn't seem to be a huge difference between framerates no matter what I try, so there's definitely something wrong in your setup.
You could try, but I feel like it might have a similar issue.
There is a noticeable difference if you have a distance threshold.
in this case, I asked it to damp towards [1, 0 ,0], but to stop if it got within 0.5 of the destination
The point is that the time from point source point to target point wouldn't change regardless of the framerate
it ran for 0.2 seconds with a delta time of 0.1, 0.01, and 0.001
it terminates sooner with a smaller timestep
however, i wouldn't expect this to produce more than a frame's worth of difference
One possibility is that something else is manipulating the position of the player.
You're missing my point
i can try turning some stuff off
and seeing if that changes anything
I'd try turning all of it off and only leave smoothdamping in update.
Unless the values are being altered elsewhere the issue likely lies with something else.
i've turned everything i possibly could of and its still happening
Maybe just log the smooth damp value with the others off. It should be consistent.
I must be, since the entire point of that page is to explain why calculating the t factor that way gives you consistent behavior across different frame rates.
yes, the blue line is lower than the others at 0.05 seconds; this is because the blue line respresents a framerate of 10
there is no frame at 0.05 seconds at all, so it's not surprising that the blue line is below the other lines (which do have frames in that period)
Hey guys, looking for some advice rather than a problem to fix.
I have a coroutine that waits 1 second when my player leaves the ground, then allows them to rocket boost upwards. I’ve tried initialising the coroutine from inside the Update method but it runs my coroutine every frame, whereas I just want it to run once. I can’t seem to find an appropriate method when looking at the monobehaviour docs. Can someone give me an idea of how to go about this?
use a bool variable and an if statement
Right. I'm uncertain of the original issue but I'm assuming it's to do with the transition rather than the result (assuming low and high rates arrive at the ladder at the specified time but interpolated differently - extreme example: cubic vs sine)
Yes, and this method gives you the most accurate transition possible.
I’m not sure I understand mate, I’m already using a bool value to see if the player is grounded. This works fine, but for when it is false, update method calls the coroutine every frame rather than just once. How would I ensure that I only call the coroutine once?
It doesn't matter what your framerate is; if you have a frame at at time t, it will exactly fit the curve you'd get from an infinitesimally small timestep
use another bool to track if you already started your coroutine
I SEE
if (not on ground && coroutine not already started)
That’s makes sense
Thanks so much
Dumb brain moment
I'm assuming both arrived at the ladder at the same time (did not time it, on mobile) but that there were variances in the stepping
On second look, the lower frame rate looks genuinely quicker. Maybe log how quickly each finished?
Just to be clear, nobody said it wasn't. I've only pointed out that it would be the only place where they're using delta time that could cause interpolation to differ in rate - assuming smoothness was the issue and not how quickly it was completing.
I see.
I did notice that it's a bit moot, though, since that's in the "Climbing" state
Yeah, assumed smooth damp couldn't possibly be incorrect unless used incorrectly then scanned the code and thought interpolation (smoothness) was the issue rather than one being actually quicker than the other.
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
the higher fps one doesnt even have enough time to finish
Why not? Do you no longer call the line?
like getting onto the ladder stage
Got to open a browser real quick
Maybe the issue is with the coroutine then, and not the SmoothDamp. You should log how far the smoothdamping gets before changing to the next state.
How are you controlling frame rates?
That's why I suggested isolating it entirely.
If you're modifying the time, maybe yield relative to real time
Application.targetFrameRate = -1;
Application.targetFrameRate = 20;
yeah im gonna do that once i get home
cause i have to go out
So if anything, you've determined that the coroutine is stopping prematurely
or the smoothdamp isnt fast enought because of framerate
Pretty certain that unless you're simply skipping calls to it, it should behave as expected.
hey anyone know why the SpawnInventorySlot method is not correctly acquiring the InventoryItem gameobject? And yes it is assigned in the field of the inspector. Here is the code https://paste.ofcode.org/YxXE9qQDCmkpsKKfkiE92p
Are you getting an error
I am not. PS here is where im calling the method https://paste.ofcode.org/A33cjg7qHxjB6efFedqFrh
I have a base class called EnemyController which has a variable called EnemyData. SlimeController extends EnemyController and I want SlimeData to also extend EnemyData. How do I do that?
in the instance of inventorymanager
Have you checked if any of those items were null?
So what is the issue you're having? What are you expecting to happen versus what is actually happening
Make a class SlimeData that extends EnemyData
If your if statements aren't running and ur not getting a error then one of the if statements null check is actually null
im expecting the InventorySlot prefab that is assigned in the insepctor to instantiate in the ItemContent reference that is also signed in the inspector
Okay and what is happening
but how to override EnemyData with SlimeData in SlimeController so I could use SlimeData methods?
You wouldn't. If you need to use methods unique to the slime data class then you need to have a reference of type slime data
Why would you have methods unique to this data type though?
When I assigned the Onclick in the field of the inspector for the button, and I click the button the Inventory.instance.SpawnInventorySlot should spawn in the instance in the itemcontent..but it seems that its just not instantaiting at all.
Inventorymanager.instance.spawnInventoryslot*
Where it'll take you from one value to the other within the respected time provided you give it a non modified velocity variable and large enough max speed @tender stag
Check if the null checks are actually null inside of the SpawnInventory Method
Where does the debugs stop?
Okay, so, what function does the button call?
woops a bit long sorry
the butto ncalls the InventoryManager.instance.SpawnInventorySlot basically
Wait which method is wrong then?
What do your logs look like
Now I'm confused
So does it get called via a unity event? What was the method you just posted
It gets called with a UI button
So it looks like none of these else conditions where you log a warning are being run, but it could also mean that literally nothing is being called at all
So put some logs in the case where things "work" instead of only for errors
Buttons use unity events just a fyi
Log things like inventoryItems when you get them
Make sure they're what you expect them to be
okay hmm...im thinking it is a problem with the SpawnInventorySlot method but I am searching... and it looks like it all checks out...
Just put the logs on expected paths like digiholic is suggesting...
oh yes why didn't I just do new SlimeData data
okay will do
I put this "Debug.LogWarning("InventorySlotSpawned!");" after I call InventoryManager.Instance.SpawnInventorySlot and I get the log in the debug when I trigger the event, but still not InventorySlot Instantiation https://paste.ofcode.org/yUFhYUWTZqde4ugxpqKWb9
Can anyone suggest me a best source or course to Begin my C# Code Journey ? Thank you
Thank You Brother
Well there's no Instantiate() call som I'm guessing it's inside the InventoryItemController.AddItem() method?
I think im figureing out the problem here...im trying to call the additem from the Slot that hasn't been instantiated yet in the SpawnInventoryItemSlot prefab....
yes
So I need to create another additemToInv method I think
will tell if this is it.
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
hello all
Im new to coroutines and Id like a hand working out why my coroutine isnt ending early
IEnumerator RocketBoost(float boostTime, float waitTime)
{
rocketBoostRoutineStarted = true;
Debug.Log("coroutine started");
if(ColliderEvents.playerGrounded == false)
{
yield return new WaitForSeconds(waitTime);
Debug.Log("waittime over");
}
else
{
rocketBoostRoutineStarted = false;
Debug.Log("Landed before boost");
yield break;
}
}
Heres the script
show how you try end early
my script is above
nothing here would stop the WaitForSeconds
I see
i thought that when the else statement was true, it would end the whole coroutine
well yeah It wont wait, are you sure the bool is true?
it would
Well Im still getting the WaitForSeconds debug.log after the player hits the ground
then ur bool isnt what u believe it is
then you already hit the first if statement
therefore second else statement is not ran
I see
Okay so how would I stop the WaitForSeconds
You would need to store it in a Coroutine then stop that
Coroutine theBoost;
theBoost = StartCoroutine(etc..
if(someCondition)
StopCoroutine(theBoost)
^ you'd need to do something like that
Where would I need to place that in the code
step outside the coroutine (for managing the coroutine)
Inside the If statement?
well there are 3 seperate parts
no. not if the if is inside the coroutine
first you declare the variable inside the class, outside the methods basically
listen up students.. the teachers talking
then whenever you call StartCoroutine
replace it with myroutine = StartCoroutine
oh and put StopCoroutine in a separate method you call whenever
where's the paddle!
np . come back if something breaks :p
then u can stop the coroutine w/ ur if conditional elsewhere. perhaps in the update. like (if ur coroutine is running.. and this conditional ends up being false.. stop that coroutine (now that u have a reference to it) @hazy crypt
Im not sure I completely understand but Im gonna have a go and see if I can work things out
If I still dont get it ill come back
Dont want to go in circles and waste your time
which part are you confused on?
I think im not understanding exactly how coroutines are executed and written, the order seems to be different to writing other things like methods which Im more familiar with
//rocket boost
if (ColliderEvents.playerGrounded == false && rocketBoostRoutineStarted == false)
{
StartCoroutine(RocketBoost(1f, waitTimeBeforeBoost));
Debug.Log("start boost coroutine");
}
if (ColliderEvents.playerGrounded == true)
{
StopCoroutine(RocketBoost(1f, waitTimeBeforeBoost));
Debug.Log("stop boost coroutine");
rocketBoostRoutineStarted = false;
}
once you call a coroutine it runs.. and its over
because youre not storing the same coroutine
you have to create a reference to a coroutine and use that reference to call stop on it
so it know which coroutine to stop
Okay, and I can declare it at the top of the script
thats why we do theCoroutine = StartCoroutine
StartCoroutine returns a Coroutine object
do i need to declare the object type like with variables
var
private Coroutine myCoroutine
you cannot use var at class level
if (ColliderEvents.playerGrounded == false && rocketBoostRoutineStarted == false)
{
rocketBoostCoroutine = StartCoroutine(RocketBoost(1f, waitTimeBeforeBoost));
Debug.Log("start boost coroutine");
}
if (ColliderEvents.playerGrounded == true)
{
if (rocketBoostCoroutine != null)
{
StopCoroutine(rocketBoostCoroutine);
Debug.Log("stop boost coroutine");
rocketBoostRoutineStarted = false;
}
}```
private Coroutine rocketBoost;
private void Awake()
{
rocketBoost = StartCoroutine(RocketBoost(1f, waitTimeBeforeBoost));
}
Now I have this
that'll run the coroutine on the first frame.. is that something u want?
basically this
forgot does stopping set it to null or you have to explicitly say so ?
it may not work.. but its the gist of it
No, I want to reference the corouitne
Ill try again hold up
thats what rocketBoostCoroutine is for
you just need to declare it (which you have in snippet you sent)
Oh I see, sorry I didnt see your code
It had already scrolled by
Ill implemetn now
thanks
// Store the IEnumerator without starting it
rocketBoost = RocketBoost(1f, waitTimeBeforeBoost);```
Yeah that makes sense
StartCoroutine(rocketBoost); // start it when needed```
if you send an entire class, use a link
i think thats how it works
oops, my bad. want me to do that?
yes !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.
damnit
Hey Hey! How can I make it so the player has to be within a certian field of view before it moves to the player?
maybe deleet the old eye sore?
@rocky canyon It works perfectly, thank you a million times over!
I already did?
no prob 👍 thank @rich adder as well
@rich adder Thanks mate!
np 🙂
❤️
I usually use a Dot product for that
wdum?
magic math stuff..
good video example :
https://www.youtube.com/watch?v=xlnkTEyAx7Q
Download the Source - https://game.courses/dot/
Determine if an object or character is in front of another, seen by it, or behind it in Unity3D with this simple 2 line c# script. Discover the power of Vector3.Dot and how to use it in a few seconds to make your AI better.
Architecture Course - https://game.courses/architecture/
Become a Member ...
these functions really are godsent lol Aint no way i knew how to make dot product just by writing it out
if i remember correctly i use Dot product for this mechanic
same principal.. i could just offset it.. to have a 180 degree in front
i honest hate using them.
confuses me if im modest
BUT your absolutely right.. it'd be ten-fold as tedious if they didnt exist
all the Mathf functions too 😮
Mathf is probably my favorite
soo much goodies inside
ive never looked inside the full thing.. my brain might explode 🤯
all the stuff i hated doing in school now comes back to haunt me lol https://docs.unity3d.com/ScriptReference/Mathf.html
here we go.. let me shield my computer
what sucks is for me to vizualize alot of this stuff i have to make examples
lol,, how many comments do u want?
- yes
im just giving them grief.. b/c honestly im glad they're there
❤️ ya Unity Staff 🙂
@rich adder is there any other special classes that worth peeking at? imma book mark a few of em
so many! depends what context :p
various random utilities I found interesting like
https://docs.unity3d.com/ScriptReference/ColorUtility.html
(its the simple stuff sometimes ) 😛
yea, forget i asked.. theres just too many... all of em are really interesting
Color, Vector3, etc
Yea, lmao, RIGHT! im looking at Color atm
jeez Quaternion.. 👀 i'll forget I opened that one
it gives you a new appreciation of how important game engines are to the layman's of the world
wait im confused.. wheres Random.Range?
does partial have something to do.. is there more pieces of this elsewhere?
Random is a partial class, there are bits of it all over the place
ahh, that makes sense.. soo u can have multiple static classes?
in different pieces?
it's one class, just written across multiple files
omg, thats super interesting..
ive never knew
partial classes are super cool
and the compiler will just put them together?
(in the abstract sense) that i can call w/e function that corresponds
wild bro..
what is the partial part called?
yes, as long as all the bits go into the same .dll, you cannot split a partial class across dll's unfortunately
ohh thats outside my skillset anyway (for now)
partial is very useful for code generation purposes
what you mean by unfortunately? what usefulness am I missing?
along with the interesting @identifier syntax
whats the partial bit called?
which lets you use anything you want as a identifier, including keywords
it's a keyword
i'm not sure if there's anything more specific to asy
keyword modifier
oh okay.. was just curious so i could loook up other things similar
b/c i really do find that interesting..
well say you had a .dll for Unity and a .dll for Windows and a .dll shared by both, it would be nice to have a partial class in all 3
ohh okay.. yea that makes sense
the class needs to be fully defined before you can compile it, hence that not being possible
i actually dont much about them other than
protection level type and name
not even sure what static is.. tbh and thats sad
i know what it does obv.. but not what its called
static modifier ?
was just about to send this..lol
the real MVP today
if you look at docs on the left side, they got all the good stuff
a small thing most people don't know is that adding the 'sealed' class modifier will actually create a faster and more optimized version of the class. so that actually has compile implications, something public, private, abstract etc, etc, does not have.
don't you still have to resolve virtual sealed methods, since there could still be several targets (any class you inherit from that also has that virtual method)?
or is the improvement somewhere else
'virtual sealed' does not make any sense, because sealed means that you can't inherit from that class
can u elaborate.. where at?
I mean a virtual method you override from a parent class.
In the following example, Z inherits from Y but Z cannot override the virtual function F that is declared in X and sealed in Y.
makes me feel dumb when i read stuff like this 😢
public class Parent
{
public virtual void Foo() { }
}
public sealed class Child : Parent
{
public override void Foo()
{
base.Foo();
}
}
e.g.
I'm just curious about what's "faster" when a class is sealed
all these goodies!
honestly their docs is solid af
You'd seal it if you aren't wanting any other class to override the member - this class has already override a virtual or abstract member and thus sealed this from any other class along the chain.
A sealed member forbids any derived class from using override with it
When a class is sealed in C#, it means that the class cannot be inherited, and no other class can derive from it. This restriction can lead to certain performance optimizations by the compiler and runtime. Here's a brief explanation with a code example:
// Sealed class
public sealed class SealedClass
{
public int Calculate(int a, int b)
{
// Perform some calculation
return a + b;
}
}
// Inheritance example with a non-sealed class
public class BaseClass
{
public virtual int Calculate(int a, int b)
{
// Perform some calculation
return a + b;
}
}
public class DerivedClass : BaseClass
{
// This class can be further inherited
// Additional functionality can be added
}
chatgpt explanation 😄
In terms of speed or performance, sealing a class can potentially enable certain compiler optimizations because the compiler knows that there are no derived classes to consider. However, the impact on performance is usually negligible in most scenarios.
tbh I don't remember the nuances, I just internalized that the IL code will be different when using 'sealed'. and in a normal .NET jit application it's then able to optimize in ways it can't with 'normal' classes. but using mono or IL2CPP might yield different results in a unity context.
often minimal he says
Note: The sealed modifier is primarily used to prevent unintended derivation, but it also enables certain run-time optimizations. In particular, because a sealed class is known to never have any derived classes, it is possible to transform virtual function member invocations on sealed class instances into non-virtual invocations. end note
from the spec
that makes sense
ya, see makes me feel dumb.. b/c i wouldn't know or be able to set up any system that I could forseeably need anything like that..
the C# specification is the place to look for the really fine details
since it..you know, fully specifies C#
but to all the advanced coders out there.. im assuming its helpful.. so with purpose i suppose
If your compile time type is Child, you positively know that the runtime type is also going to be Child
So you can turn that into a non-virtual call
Mainly for explicitness in constraint
oh i thought u meant in the extracted unity class repo
ya.. i been reading over the docs more and more often..
And the optimization if you care
where its applicable ofc..
yes feels way less robotic than it used to be back in the day when I tried getting into early MSDN
anyways, that was my hot-tip, every class that can be sealed, should be sealed. gotta save cycles wherever you can! 😆
all good!.. happy for everyone that chimed in
i didn't mean to start an avalanche
what i've learned.. programming languages are way way more involved than a beginner can even perceive
not all of them, just the good ones
im balls deep in the new input system atm
i needed a break.. lol
using a Radio controller and ran into issues..
theres deadzones programmed into the Firmware of the radio.. soo I get values from .-72 -> + .72 and trying to figure out how to deal with it
magic numbers suck cs private float NormalizeInput(float inputValue) { // Map the inputValue from the range (-0.72 to 0.72) to (0 to 1) var zeroToOne = Mathf.InverseLerp(-0.72f,0.72f,inputValue); return zeroToOne; } but that's the best i know to do..
imo The solution is to have a Calibration prompt before hand..
that can register the top most and lower most values and use them in code
Yaw Pitch Roll can be one Vector3 input. Maybe also a, b, c, d, not sure what they represent.
even if its 4 actually inputs?
Couldn't you use the Deadzone processor instead? https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Processors.html#axis-deadzone
didn;t know this existed 👀
i tried to change it in the input system.. but i couldnt get it to work correctly
Divide the values by 0.72 and you ought to get values in the range (-1, 1)
You mean the Normalize processor?
they're toggles on the radio
nah then they'd only get 0 or 1
when i normalized the inputs i still got the -.7 - +.7 but it coulda been user error tbh
the throttle still feels bad tbh.. the values seem to skip alot of numbers
Not according to one of the examples in the doc.
// Normalize 2 against a [1..5] range. Returns 0.25.
NormalizeProcessor.Normalize(2, 1, 5, 1)
Deadzone just means it will stay zero until you've moved the stick past the deadzone.
the names are a bit misleading
ohh yea, thats not what i need then
interesting
Normalize is a remap
I see
Normalize Vector 2 is a normalization
I guess that "Normalize Float" would be...very pointless
public float MyEpicFloatNormalizer(float input) => 1f;
ya, it didnt do anything from my perspective
Did you set the min/max to -0.72 and 0.72?
im using floats b/c the control surfaces are actually split
its not 1 input. but 2 inputs combined.
but i did think about trying to use vector2
damnit..
i did not 🤦♂️
this is the first time using new input system..
That feels like an implementation detail that your game doesn't need to know about. But if the goal is to only support this specific controller, then I guess you can do it this way.
i haven't figured out how to use different inputs quiet yet
You can make a composite Vector2 action out of two float controls
i'd like to be able to use a gamepad as well..
im just using this controller.. b/c im trying to make a FPV drone simulator.. and it fits well
since its an RC radio
oops, I was mistaken; I was thinking of making a Vector2 action out of four controls
but yea, for it to be useful to anyone besides me.. i need find a way to support both RC radios, and Gampads (PS4-5) (Xbox)
i got alot of learning for the new input system tho..
i've fallen behind
every tutorial i watch is 100% different.. i can't find uniformity in any of em
[SerializeField] private RadioControls radioControls;```
```cs
private void Awake()
{
// create new radioControls
radioControls = new RadioControls();
// set input actions
thrust = radioControls.Base.Thrust;
yaw = radioControls.Base.Yaw;
pitch = radioControls.Base.Pitch;
roll = radioControls.Base.Roll;
this is the way I settled on
SOs and gameobject script
There are a number of different ways to get input.
sooo no one right way i suppose
These pages describe the different ways.
thanks i'll give it a look
You're using the "Generate C# Class" option here.
yessir
i gathered this was the better way
than to use the component
It's convenient, yeah. It's very similar to using InputActionReference
you just reference members of the generated class instead of assigning things in the inspector
both of them give you access to InputActions
but not sure its the way i need to go.. since i want to support different radio's.. theres 100s of radios.. so i think i need a calibration scene..
that can grab any input from any style radio and map them to the correct axis'
thrust, yaw, pitch, and roll
I haven't gotten into rebinding yet.
ya, im probably over extending myself.
but what bettter way to learn than to jump in the deep end i suppose
#restoftheowl
!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.
https://gdl.space/evenurovey.cpp
So i'm making a 2D game and i've gotten the movement down but now my dash just doesn't add the the rigidbody force or at least very rarely and it doesn't move. I need to have it dash but it isn't doing it.
You're doing this every single frame: rb.velocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y);
where in that code do you suppose a dash would have time to happen?
I did have chatGPT help so that may explain it but the dash should happen in the IEnumerator Dash
You're going to need to do some of your own thinking about the code soon
Again, think about it. You're setting the horizontal velocity every single frame
directly setting it
to an exact number
I know, trust me. I understand code but not to make it. I fail my test cause of creating it.
how do you suppose a dash that should happen over multiple frames could possibly work in that context?
hey, add this dash force to the velocity!
nope, imma set the velocity to What I want!
fine then! 😦
Hey guys, so right now, I am programing my animations by playing them through code in vs. The problem is that I want to play a certain animation before another animation when a player hits a button, but I don't know how to do that. For example, before playing the running animation, there is an acceleration animation to be played before hand. Here is my code so far:
https://hastebin.com/share/ahewoyojop.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Declliration eh?
yea sorry for the spelling errors
lol no prob..
is there a way to transform.rotate.up?
you can play ur acceleration animation.. and then check when its finished to play the next animation
how do I check when an animation has finished playing?
transform.forward = Vector3.up;
(!myAnimation.isPlaying)
or myAnimation.isPlaying == false
ohh ok that is very helpful
as long as its not looping it'll finish
What exactly do you want to accomplish with this line of code?
I'm trying to make cointrollable hydraulics for my vehicle (not fancy hydraulics, but like work hydraulics, for the tow truck chassis)
I am really stuck on this part of it and could honestly use someone to help me hash the details out in code. I understand the code, but I feel like some of what I need to do is beyond my knowledge of the 3D world space
@wintry quarry
https://www.youtube.com/watch?v=HIeRuyRL22A i made an excavator using hinge joints
Recreating a hydraulic system I used on an early project of mine, where I built a physics driven excavator in Unity.
but what are you actually trying to do with that line of code
Move a fucking arm up and down
I don't see what transform.rotate.up has to do with hydraulics
are you wanting it to be physically realistic?
or in and out, depending on the arm. But it all has to be in coorelation to eachother
move things in local space would be my suggestion
muahah
At the moment I dont care, I just want the damn thing to move within realistic constraints
Hello, I have a question regarding on how I can make stiff joint between object in a way that they dont start stretching
just setting localPosition to some desired value and clamping will do it
if you want physical realism look into ArticulationBody and Prismatic Joint
@rich adder let it be known i can't control an actual excavator, lmao
so what did you use to make the arm portions move on button pressed held @rocky canyon ?
i moved the anchor point of the hinge joints that i used to connect the arm pieces
Right now I just have my arm pieces, and I have their origin points set to their pivot locations, everything moves how I want it to manually, I just cant get it to all move properly in code. The up and down arms move fine, but the slider arm does not
oh dang you did the hard part first ? lol
you keep the connector anchor point where it is.. and change the anchor point of the hinge joint..
it looks like I am having an error
that will pull the connected arm towards the center of the gameobject ur using to contain the hingepoint
string doesn't have method/property called isPlaying
ur trying to see if a string is playing
strings dont play
animation clips do
playerAnimation.idle.isPlaying
not sure why ur converting it to a string
but I am trying to refrence the name of the animation right?
im a physics lover.. i know how they function... but can't control one worth a flip
no u reference the actual animation clip..
u may in ur code need to use a string for w/e reason.. but asking if it isPlaying is not one of those reasons
yeah that part gets diffcult, esp when you start adding suspensions n junk
https://github.com/SpawnCampGames/Excavator-Physics
oh snap, i actually have the entire unitypackage available
ok then how do I get access to the clip so that I can use the function?
what type is playerAnimation and idle
@rich adder in case u missed it https://hastebin.com/share/ahewoyojop.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
playerAbunation is an enum, and idle is the animation within the enum
they are Enums 🤔 ?
yea
soo ur using a enum just for the string? (name of the clip) ?
so idle would not have a bool in it
no
yea, I find it much easier to do so
until u need to access the actual clip Lol
he wants to play a clip (acceleration) before he plays a walk/run animation..
i suggested he use isPlaying.. so he can know when the clip finishes before calling the next animation..
but i wasn't aware of his setup
oh that makes sense then
you can just have the clip have Exit time no?
this way it has to finish before going to next state
I dont have all the context, but you can always use animation triggers
@rocky canyon That looks like the behavior I am wanting, minus the actual slider pistons, I think because I don't have the additional slider pistons the design you have is a little more advanced that I need
i dont know why people don't use the animator more often..
its like everyone hard codes the animations..
i dont get it
yeah I almost use blend tree for anything
that may be true.. it was an experiment to see how realistic i could make the arms move..
(mimicing actual hydraulics)
it may not be best suited for what ur doing
I recently discovered the animator for UI stuff, before always used DoTween 😄
can you share code/ video of what u have so far? so we have some context to work off of? @sterile moon
tweens are more flexible / can be changed realtime
i've always been told not to use animator on UI.. b/c it has to redraw it every time u do
so i specifically use tween for it..
and that
idk know 😄
What I have right now is 2 primary arm pieces that need to move up and down, a third arm piece that needs to slide in and out, a fourth part that needs to tilt left and right, a 5th part that needs to swing two parts open and closed, sounds easy right
sure
lmao
for a system like that.. make sure u know the difference between local space and global space
its really important when moving pieces around like that
but aren't there really any other way to get access to the animation clip? Cause I thought that you do that by using their names.
Oh i thought they fixed that
I showed you how
if u want it to be simulated.. u can just rotate the pieces w/ code
you mean the clip from animator that is playing?
yes
or use IK
wouldnt it be this piece that rotate
AnimationClip animationClip = playerAnimator.runtimeAnimatorController.animationClips
.FirstOrDefault(clip => clip.name == animationClipName);``` i found this crazy ass code
oh shoot, I didn't see that
and they are all connected with parent/child objects or physics joints?
Partent child connected so they all move and stay connected like I want them for now
ohh soo if they are connected using the hiearchy u can just use translation to rotate them
I have the arms up down movement working, minus clamping
transform. -> rotate
Yeah been there, BUT the issue is I have is when going to the slider portion
can u share the !code for the part that u working on?
📃 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.
That third picture DOES NOT rotate. It needs to slide in and out going in and out of the second arm no matter what position the second arm is in. No one has seemed to get that part yet to be able to help me
Current code involved with moving, key binds are just all over the place for testing
Nope, next imasge after that needs to slide. The part that you have there is what it needs to slide in and out of
ok I got it, so it should look like that for what I want, right?
}```
This guy slides
in and out of this guy, no matter what angular position this is at
Im apparently making a porno, don't mind me
ok i think i understand now
soo.. the 2nd image rotates up and down.. and u want the first image to slide in and out.. no matter the rotation
Exactly
this whole setup screams IK
phew, lmao
yup, thats a good way to do it.. im a physics junkie.. so i like to use hinge joints and manipute the anchor points..
(gives it a real jerky realistic feel)
but an arcade feeling might work for this guy
I would really love, and honestly would pay for you to help me get it going, physics would be ideal, but id settle for arcade right now just as proof of concept
with an IK system u could rotate the very end point (the bucket) and all the other things would just work
you tried it?
Thing is though they all need to be controlled individually
On a real tow rig, each piece of manipulated through its own lever
true true
@swift crag @teal viper im back now
I was thinking of learning IK for this too, but that does movement in relation for all objects
i still havent figured it out, any ideas?
i think ur setup is good
yea... the if statement returns true immediately
but u really should be using transform.localPosition on alot of these pieces
the ones that are parented to other pieces
it does not return true when the animation finishes
weird
just use animation events
prob be easier to deal with
hi, sorry too bother but I'm making a medieval game and I just want to get an idea on how to count up hits until it reaches a certain number and then an animation will play. Could anyone tell me how to do so if not somewhat of an idea will do just fine. Thank you
^ this is probably ur best bet.. it would require u to redo some of ur script.. but it would be better inthe long run
me?
int hits;
public void IncreaseHits(){
hits++;
}
Debug.Log(hits)```
the guy with the animation clip problem
ahh
ty
public int maxHits = 5;
private int currentHits = 0;
void OnHit()
{
currentHits++;
if (currentHits >= maxHits)
{
PlayAnimation();
currentHits = 0; // to reset
}
}```
So, how would I use localPosition in this plan, as I dont see a way to access localPosition.rotation.y
also would i make another paramater like an int one?
hmmm, alr ill try to learn it
localRotation
theres transform.position and transform.localPosition, same with rotation, transform.rotation and transform.localRotation
you just declare them
access modifier - variable type - variable name
eg
private string helloWorld = "Hello World";
ok ty ty
And I would just use transform.Rotate to actuate the move right?
i need this tattoo'd on my forehead.. so i can just facetime all these guys.. it'd be so much easier
to actuate a rotation yes
for a move it'd be position
go hard or go home!
face tats are trendy
how much time have u spent learning unity?
Why would .Rotate cause something to move
But the lure isn't the thing that's rotating
thats y i asked how much learning he's done.. it seems he's confusing some basic principals
.position, .rotate.. very very crucial things
Im good with the code, and I'm good with the 3D world, thjis is my first time really mixing the two hardcore outside of just theoretical principals
well, thats fine.. ur bound to run into issues.. this is the troubleshooting stage..
try changing some things to local space..
it would make ur functionallity very differently
Way ahead of you, already switching all parented arm objects to local
cool cool, just do that and test.. and see what happens
then re-iterate and try again
transform up is z axis right
transform.up is the local Y axis of that object
depends on whether its rotated or not
Y axis
Z is forward
X = left right, Y = up and down, Z = forward and backward
And here in is where my problem lays I think, I have no clear axis for mvoement for the slider it seems
X is red, Y is green, Z is blue
@swift crag @teal viper the first smoothdamp runs at unlimited fps and the second runs at 15
u can see how the times of how long the smoothdamp took to finish
the one with lower fps was faster
i just want to congratulate you.. ur progress has been epic
no im serious
thanks man
constantly progressing.. and learning new things all the time
if i could only figure out why smoothdamp is so fps dependant
multiply it with time.deltaTime
dang, my hand had a cramp while trying to do that
it took me way too long to find the correct hand gesture..
soo many different axis's in different software
then why is it frame dependent then?
lol.. u got me entriqued as well.. imma do some testing.. standby
we've been trying to figure this out like half of the day
points towards one of your params... like velocity... you sure that per second and not per frame?
how do i make a slider be saved? for my volume slider, the volume itself is saved but the value of the slider isnt
you have to reset it onload
yeah
just do it manually using the value u saved
so what you set value of slider = volume ?
If your sliders min max values are 0-1 yes
you'll save the value using whatever method you like, then when the game starts you load that value and assign it to the slider.value .. this is a commonly used class for that kinda stuff: https://docs.unity3d.com/ScriptReference/PlayerPrefs.html
problem is that it doesnt save when you switch scenes not even if you close the game
im actually tweakin
im making a new project
newer unity version
just to see if it might be that
which i know it wont
thats what that class I linked is for
👍
you can use additive loading to always have ur sliders loaded.. or u can initialize them each load
ya, doubt that'll change it.. I'd try a simple test class first.. make sure it ACTUALLY works the way you expect (via lotsa debug.log's), with known/less variable inputs. Then start addin' in the variable inputs till you find the culprit.
//exit from settings option
public void UpdateGameSettings()
{
// Get the GameSettings from the GameManager
CurrentSettingsMemory gameSettings = GameManager.x.Settings_Memory;
gameSettings.musicVolume = (int)(musicSlider.value * 100);
gameSettings.sfxVolume = (int)(sfxSlider.value * 100);
gameSettings.mouseSensitivityX = MouseSensXSlider.value;
gameSettings.mouseSensitivityY = MouseSensYSlider.value;
if(invertYToggle.isOn)
{
gameSettings.invertY = true;
}
else
{
gameSettings.invertY = false;
}
gameSettings.qualityLvl = (QualityLevel)GraphicQualityPreset_DropDown.value;
gameSettings.fieldOfView = (int)fovSlider.value;
gameSettings.shakeIntensity = (int)(ScreenShakeUI.screenShakeSlider.value * 100);
UpdateVisuals();
SaveSettings();
}```
i already did that
i run UpdateGameSettings anytime a new scene is loaded.. using a Json file.. but u could also use playerprefs as Glurth has mentioned
right here
i disabled the movement script
and everything else
@tender stag do you have any code you could share?
yea exactly..
i wanna rob, inspect it
u can read from this down
what we've been trying
pretty much everything
oh hell nah, imma write a simple version
🤣 i was gonna copy and paste and see if i can see what ur seeing
lmao
translations? then
kinda like this?
take a look at this #💻┃code-beginner message
alright.. imma write me a simple cube movement script.. and a frame limiter.. brb
to figure out whats going on, I'd try more debug logs.. e.g. output of the velocity each frame, along with deltaT?
What is calling HandleLaddering()?
Also instead of doing all that angle math have you considered just using Mathf.SmoothDampAngle? Then you can just damp between yRotation and yTargetRot
why is my stuff Yellow all of a sudden?
HandleLaddering is in update
i might consider just using lerp at this point
but i just wanna know why this is happening
its not gonna let me sleep otherwise
{
private const string FullscreenPrefsKey = "IsFullscreen";
void Start()
{
// Load the saved fullscreen mode setting or default to true
bool isFullscreen = PlayerPrefs.GetInt(FullscreenPrefsKey, 1) == 1;
SetFullscreen(isFullscreen);
}
public void SetFullscreen(bool isFullscreen)
{
Screen.fullScreen = isFullscreen;
Debug.Log("Toggled Fullscreen");
// Save the current fullscreen mode setting
PlayerPrefs.SetInt(FullscreenPrefsKey, isFullscreen ? 1 : 0);
PlayerPrefs.Save();
}
}```
i have that already
so i just do that for the slider too?
yep.. preety much all the same cept this one line Screen.fullScreen = isFullscreen; (and names, ofc)
what do i set the value to be at the start? 1?
seems to work fine for me
same distance travelled..
void Update()
{
// calculate target position
float targetX = initialX + Mathf.PingPong(Time.time * moveSpeed,moveDistance * 2) - moveDistance;
// damp the smoooth
float smoothX = Mathf.SmoothDamp(transform.position.x,targetX,ref velocity.x,smoothTime);
// make it move
transform.position = new Vector3(smoothX,transform.position.y,transform.position.z);
}```
Same for SmoothDampAngle
public class SmoothDampTest : MonoBehaviour
{
public float timeStep = 1f / 60f;
public float smoothTime = 3f;
[Range(0f, 360f)]
public int targetAngle = 0;
private float _angularVelocity;
private Vector3 _eulerAngles;
private IEnumerator Start()
{
_eulerAngles = transform.eulerAngles;
while (true)
{
yield return new WaitForSeconds(timeStep);
_eulerAngles.x = Mathf.SmoothDampAngle
(
current: _eulerAngles.x,
target: targetAngle,
currentVelocity: ref _angularVelocity,
smoothTime: smoothTime,
maxSpeed: float.MaxValue,
deltaTime: timeStep
);
transform.eulerAngles = _eulerAngles;
}
}
}
right so when i change my scenes, and the full screen toggle is un loaded, when i go back and open the options menu again, it changes itself back to full screen
public class ToggleFullscreen : MonoBehaviour
{
private const string FullscreenPrefsKey = "IsFullscreen";
public UnityEngine.UI.Toggle Toggle;
private void Awake()
{
if (PlayerPrefs.GetInt("ToggleSelected") == 0)
{
Toggle.isOn = true;
}
else
{
Toggle.isOn = false;
}
// Load the saved fullscreen mode setting or default to true
bool isFullscreen = PlayerPrefs.GetInt(FullscreenPrefsKey, 1) == 1;
SetFullscreen(isFullscreen);
}
public void SetFullscreen(bool isFullscreen)
{
Screen.fullScreen = isFullscreen;
Debug.Log("Toggled Fullscreen");
// Save the current fullscreen mode setting
PlayerPrefs.SetInt(FullscreenPrefsKey, isFullscreen ? 1 : 0);
PlayerPrefs.SetInt("ToggleSelected", 0);
PlayerPrefs.Save();
}
}```
its like its just not saving
Hey, guys! I am currently making best score and best time on my game. They will be appeared at the main menu scene. I have a round manager class where I have all of this functionality. Now the problem is that I have that round manager class attached to my game object called round manager in Main game scene. How can I move that class inside my main menu scene in order to update my best score and best time because I have only attached my game objects in Main Game to my round manager class component.
Interesting now i see lerping and smooth damp in a different light,where did you learn the ins and outs of all the lerping stuff,i only find amateur ways of doing lerp and not the right way
thats some crazy syntax
have u checked out https://gamedevbeginner.com/the-right-way-to-lerp-in-unity-with-examples/
This is another good resource https://youtu.be/yGhfUcPjXuE?list=PLrWlVANGG-ij06UCpfdxQ-LBclsWUDLt-
Not specifically about lerp vs smoothdamp, but goes into detail about time steps and interpolation
DeltaTime. This video is all about that mysterious variable that oh so many game developers seem to struggle with. How to use DeltaTime correclty? I got the answers and hope this video will help to deepen your understanding about how to make frame rate independent video games.
0:00 - Intro
0:34 - Creating The Illusion of Motion
1:11 - Simple Li...
everytime i log on to vscode to do some programming for unity, vscode does not recognise any of the unity methods e.g. Physics.Raycast()
can i have some help?
haha the named arguments?
i literally have no idea whats going on 😄
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
configure it and it will
The args are in order so named arguments are technically not needed, but it's useful if you have a method that takes a lot of them, or want to explicitly show what each parameter does
wait, is that the same thing as SmoothDamp(x,y,z,t);
↑↑
It's SmoothDampAngle which is meant for animating angles. Just this method signature https://docs.unity3d.com/ScriptReference/Mathf.SmoothDampAngle.html#:~:text=public static float SmoothDampAngle(float current%2C float target%2C ref float currentVelocity%2C float smoothTime%2C float maxSpeed %3D Mathf.Infinity%2C float deltaTime %3D Time.deltaTime)%3B
ahhh, ive never seen that before..
Yes you do that if you want to pass the arguments in another order (but why would you do that), or if there are optional arguments you want to skip, eg. raycast mask without distance: Raycast(origin, direction, layerMask: mask)
pretty cool
i didn't ignore ya, i just don't see the issue
haha yea i think it's a lot easier to read. it's explicitly showing how my variables map to the method arguments. I don't do it this way all the time, but it's helpful for methods with lots of args, or methods where it's not immediately clear what youre passing without reading the source of the method
so it should be working?
Most code editors (Visual Studio and Rider included) will have an option to show argument names inline
Disabled by default, I have them enabled for var and lambda argument types
i rely on tooltips
but cool to know that exists
Yea I have it disabled as well since I don't always want to see arg names
ya, can make ur code pretty chunky
imo it should.. can you debug it.. or visually inspect it..
i've never used playerprefs tho, im a JSON fan boi.. but idk
honestly as long as it looks right thats fine for me
its for a school project so i dont necessarily need it to be working since they dont see it
lol.. what?! as long as its working should be ur go-to
classic
makes up cited sources for research paper
what does yellow signify? i cant find anything on google
hello, how would I make a gameobject disapear without destroying it?
deactivate it
GameObject.SetActive(false)
okedoke ty ty
or disable its renderer
MeshRenderer.enabled = false
You are infected. Please respect a quarantine period, or the end of symptoms, whichever comes first.
Idk, seems like a theme thing? Is it taking your Windows accent color now? I haven't started the 2022 version in a while
its usually blue..
tyty
nah, my theme is brown
no clue.. i'll figure it out..
or i wont.. regardless lol
tf i figured it out...
i never changed it tho.. oh well
Ahh neat that explains it
yea.. i feel dumb
I don't have the option so looks like it's from a recent update. By default mine are only outlined blue
I just tried to instantiate a new Vector3 but apparently it is an ambiguous reference between unity vector3 and System numerics Vector 3. Any help?
Remove the using System.Numerics; at the top, it also provides a Vector3 so your compiler cannot guess which one you want, Unity's or Numeric's?
Why do you have using System.Numerics;?
if you don't have a good reason for it, remove it
why is it even there
probably an auto add
yes
you weren't paying close attention and added it from an auto suggestion
oh ok
you can use whatever you want but you most likely want UnityEngine.Vector3
ill make sure to check
Yep Quick Actions, or if using VS22 it's added automatically if you select the wrong element of the completion list
to start out yes, as u add things u might need more..
like UnityEngine.UI, or System.Collections, etc
yea im a beginner so im not really sure
Ive used this channel so much today lol but! my particles are spawning when the game starts and not when the enemy dies could someone help perchance?
How did you set things up to try to make them spawn the an enemy dies?
It's going to be as easy or hard to run as you make it.
like this
if thats what u mean
ok and where do you call OnHit from?
Ok so is this running when the game starts? Use Debug.Log to find out
if it's not, then the particles are coming from elsewhere at the start of the game
probably you left an object with the particle system on it in the scene with Play on Awake
is that it?:/
that just grabs a reference to the Particle System
ok ok
and saves it in a variable
sry but where should i put debug.log?
OnTriggerEnter and/or OnHit
thats weird
You need to actually write a message to log
why the hell is it slower for me
Do you have an actual question?
slower and faster
depending on framerate
like what sry (Im thick)
just something you will notice
like "OnTriggerEnter was called" @shadow rain
Use !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
as for people to work for free, that's called slavery
and it's outlawed in most places
yes you don't need to show a screenshot every time you write some code
now run your game and see if that is running or not
im just gonna change smth
how would i reference the skinned messh renerer?
!code Slime.SkinnedMeshRenderer?
📃 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.
Same way you reference ANY component in Unity
make a serialized field and drag and drop it in, or use GetComponent or whatever
ok so
it does work at the end
so i was right
kinda
BUT i disabled the whole slime instead of the renderer causing the particle system to be disabled too!
the only problem still is that that particles still play at the beginning
AND BOOM FIXED!
play on awake ❌
this is great!
Hi. how can i put a decal where a gameobject touches another gameobject surface?
This is the coding channel, maybe try asking in #💻┃unity-talk
Why are UI elements not showing up if I enable them in a certain scene? They appear and disappear in another but not in this scene :(
Not related to code but I'd suggest pausing and viewing the object from the Editor scene view - assuming that's the game view window.
Maybe they're not in the right place
It may be doing what it's supposed to be but simply.. what he said 
"Screen Space - Overlay" canvases are placed in the scene so that world space and the canvas's local space are equivalent
you get a very large canvas as a result
Idk sorry. Your code has a lot more going on than the simple test I did so it has to be something to do with how you're using the function. I would start as simple as possible, make sure it works, and then add complexity incrementally
idk man.. 1 running full speed, and the other only being 15 fps.. .03 is pretty minor
the coroutine stops the smoothdamp
after a like second
so the 0.3 would make a masive difference
it looks like the coroutine is fps dependent
the only difference between mine and urs.. is i calculate the smooth damp (outside the transform.position)
transform.position = Vector3.SmoothDamp(transform.position, ladder.bottomStartPosition.position, ref ladderPositionVelocity, ladderStartPositionDuration); heres urs
float smoothX = Mathf.SmoothDamp(transform.position.x,targetX,ref velocity.x,smoothTime);
// make it move
transform.position = new Vector3(smoothX,transform.position.y,transform.position.z);```
heres mine
someone said that this doesnt make a difference
thats the only difference I visibly see tho