#💻┃code-beginner
1 messages · Page 252 of 1
I am using this https://gdl.space/wuvufeliqo.cs triangulator that I found online and edited slightly. When I run the code, I get the following error:
"Failed setting triangles. Some indices are referencing out of bounds vertices. IndexCount: 24, VertexCount: 0"
There isn't a code problem with the triangulator, but it seems to be doing something wrong. The problem is that it is completely opaque to me. Can anyone here see if & where something is going wrong?
Scaling fixedDeltaTime based on the timescale means that it's always doing the same number of fixed updates per real world second
Hey guys, I need a little help
Here I have this method
This method spawns an item in a position that's empty, but I want it to spawn item a few second after that position is emptied.
So I use Coroutine
But it doesn't work, the new items kept being spawned immediately
Please help, where do I have to put the yield return ?
📃 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.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FloorManager : MonoBehaviour
{
[SerializeField] private List<Transform> floorSpawnPoints = new List<Transform>();
[SerializeField] private List<GameObject> floorBricks = new List<GameObject>();
[SerializeField] private GameObject brickPrefab;
[SerializeField] private GameObject gate;
[SerializeField] private bool canSpawnBricks = true;
[SerializeField] private GameObject player;
[SerializeField] private bool test;
private GameObject brick;
private GameObject respawnedBrick;
private bool canRespawn;
private void Awake()
{
if(canSpawnBricks)
{
SpawnBricks();
}
}
private void Update()
{
StartCoroutine(RespawnBrick());
}
public void SpawnBricks()
{
for (int i = 0; i < floorSpawnPoints.Count; i++)
{
if (floorSpawnPoints[i].GetComponent<SpawnPoint>().HasBrick == false) {
brick = Instantiate(brickPrefab, new Vector3(floorSpawnPoints[i].position.x, floorSpawnPoints[i].position.y, floorSpawnPoints[i].position.z), Quaternion.Euler(0, 90, 0));
brick.GetComponent<BrickColorChange>().ColorChange();
floorBricks.Add(brick);
}
floorSpawnPoints[i].GetComponent<SpawnPoint>().HasBrick = true;
}
}
public IEnumerator RespawnBrick()
{
float timer = Random.Range(3,5);
yield return new WaitForSeconds(timer);
SpawnBricks();
}
}
The code you showed looks fine -- it waits for either 3 or 4 seconds, then calls SpawnBricks
You're starting a coroutine every single frame
So there are tons and tons of coroutines running all at once
Perhaps you wanted to start it once when the brick was destroyed
(note that if you want a range of 3 to 5 seconds, you should do Random.Range(3f, 5f))
if you give it two integers, you get an integer in the range [low, high)
excluding the high value
Where exactly does the error come from?
You should be getting a line number.
It's coming from UnityEngine. There is no error in the triangulator, just in the array that it spits out
public void render() {
Mesh mesh = new Mesh();
mesh.triangles = new Triangulator(_points).Triangulate();
mesh.vertices = _points.ConvertAll(p => new Vector3(p.x, p.y, 0)).ToArray();
mesh.uv = _points.ConvertAll(p => new Vector2(p.x / (MAX[0] - MIN[0]), p.y /(MAX[1] - MIN[1]))).ToArray();
GetComponent<MeshFilter>().mesh = mesh;
}
It is being called line 3 of render()
right now im creating all my data in a static class with static readonly dictionaries, is this a fine way to do it?
for example, all the tiers for each stat along with its weight, etc that can roll on an item
Ah, wrong order
You need to assign vertices first
You don't have any vertices yet, so Unity throws an error when you assign the triangles array
It immediately tries to validate the mesh when you do that.
i'll have to find out where..
right there #💻┃code-beginner message
i'd rather pitch the volume up and down... than scale the timescale.. not sure whats going on
it's two differeent things
ya, sadly i dont understand what thats doing..
It's setting a mixer parameter based on the time scale
I presume audio sources are reading that parameter to set their speed parameter
Completely separately, it's computing a fixedDeltaTime value based on the current timescale
void FixedUpdate() {
// Set the fixed update rate based on time scale
Time.fixedDeltaTime = Time.timeScale * initialFixedTime;
fixedTimeFactor = 0.01f / initialFixedTime;
inverseFixedTimeFactor = 1.0f / fixedTimeFactor;
}```
this part eh?
lol. math
Yes. I dunno what fixedTimeFactor and inverseFixedTimeFactor are used for
But that's what the first line is doing.
That fixed it, thanks
Yes it worked
Thank you so much
Even though my code is an absolute mess right now :)))))
Each time you call StartCoroutine, you're giving your MonoBehaviour an enumerator
By default, the enumerator gets resumed once every frame
so you had like 100 RespawnBrick enumerators all running
when an enumerator being run as as coroutine yields WaitForSeconds, Unity..waits for that many seconds!
then it resumes the enumerator again
and in this case, it calls SpawnBricks
In simpler terms, this script ensures that when you want time to go faster or slower in your game, it doesn't just affect how things look or sound but also how the physics and other calculations happen. It keeps everything in sync, making sure that when time speeds up, everything speeds up, and when time slows down, everything slows down. This can be useful for creating slow-motion or fast-motion effects in your game. I had chatgpt ELI5 lol..
that might actually be fine to mesh w/ my prototype i already have..
the only thing i do is pause Time w/ time Time.timeScale
currently thats the only thing i do
well, it's not that it makes physics run slower or faster as the timescale changes
that already happens
it keeps the number of physics updates per real-world second constant
okay. i think i understand it now.
i usually stay away from time.. but this seems to be a dependency
an enumerator being the thing that RespawnBricks returns! An enumerator "pauses" each time it hits a yield until someone resumes it
that's how coroutines work: your method does some work, then hits a yield and takes a break until Unity resumes it later
okay I did a sample run.. the TimeMaster script doesn't negatively affect my existing code 👍 thats a good thing.
soo from what ive gathered from you and other research this basically is just a supplementary system.. that basically does what unity already does..
just a bit more
This is all that it does.
By default, the number of physics updates is consistent per in-game second
Hi, i don't have a particular problem but i'm just curious
I notice that you're emphasizing "in-game"
Is there a difference between ingame second and real-life second?
Right.
Time.time measures how much time has passed when you take the timescale into account
Time.unscaledTime ignores that.
It, along with Time.unscaledDeltaTime, are useful for things like UI that shouldn't depend on the timescale
(well, in-world UI should probably care about the timescale!)
So when you change the time scale, let's just say from 1 to 0.5, then the number of physics update will be halved?
The number that happen per real-world second, yeah
Assuming the player isn't providing any inputs, this means that changing the timescale shouldn't change the outcome of physics
Ah i see
It won't run more simulation steps with a smaller timestep for each one
And, conversely, if you crank up the timescale, you don't get fewer, longer physics timesteps
Before, I thought it would just magically know to make the physics simulation run at the same speed, but do less things
when I set my game's time scale to like 50, I get dozens of FixedUpdate calls per second
Wow
yeah -- the important thing is that Time.fixedDeltaTime does not change as the timescale changes
Dang
so, by definition, we must run fewer physics updates per real-world second when the timescale is less than 1
I see i see
Does Time.deltaTime?
Wait imma be back in 3 min
It does, yes. Hence Time.unscaledDeltaTime for when you don't want to factor in the timescale
Oh i see
So if I was moving an object by adding to its position (times Time.deltaTime), I shouldn't multiply by Time.timeScale as well?
Yeah, don't factor in Time.timescale
I guess you could do Time.unscaledDeltaTime * Time.timescale, but that'd be a bit silly :p
Hi, I'm trying to run a coroutine from a non-monobehavior class. The problem is that coroutine only triggers once, no matter how many times I call it. This line yield return StartCoroutine(_currentAction); only run once.
private Action _callback;
public void SetGameEvent(IEnumerator currentAction, Action callback)
{
_currentAction = currentAction;
_callback = callback;
}
public void StartEvent()
{
if (_currentAction != null)
{
StartCoroutine(StartEventCoroutine());
}
}
private IEnumerator StartEventCoroutine()
{
yield return StartCoroutine(_currentAction); /// this
_callback?.Invoke();
}```
You'd need to make a new IEnumerator each time
StartCoroutine(_currentAction) will see that you gave it a coroutine that's exhausted and immediately throw it out
It's a bit complicated, but you could take in a function that returns IEnumerator and then invoke it
indeed -- maybe you can store a System.Func<IEnumreator>, which is a function that takes no arguments and returns an IEnumerator
StartCoroutine(enumeratorSource());
Yep, that's the one. I always have to look up between Action and Func which is the one that has parameters and which is the one with return values
So, instead of taking IEnumerator and passing it SomeFunction(), you take a Func<IEnumerator> and pass it SomeFunction
I wish it was System.Proc (for Procedure)
in Ye Olde Lingo, a procedure doesn't return something, and a function does
public void Whatever() {
IEnumerator coroutineInstance = CoroutineMethod();
System.Func<IEnumerator> coroutineMaker = CoroutineMethod;
IEnumerator anotherInstance = coroutineMaker();
}
public IEnumerator CoroutineMethod() {
...
}
there's the distinction
Unity won't open/go to Vs Code when clicking console log messages or errors, but it DOES when clicking warnings only. I checked the external tools path and reinstalled Vs Code. What am I doing wrong?
Sorry, it seems I lack knowledge about IEnumerator. Let me look at it for a moment. Thanks 😄
hey guys, is there an easy way to expose all of these variables in a collapsable panel in the editor for my monobehaviour? this just looks absolutely awful and is a constant headache
-
Do they need to all be exposed? If some are on the same object, just make them private and use getcomponent
-
you can make a custom inspector, or use something like naughty attribute or odin serializer
there are a few ways, either using a custom editor for that class, shoving all of that into a serialized class and have a variable of that class on the MB instead, or use a 3rd party asset like Odin or Naughty Attributes that include Foldout attributes
wouldn't getcomponent be kinda inefficient espescially if I was doing it at runtime tho
No
ok I think I'll try make a custom inspector then
Serialized references (like drag and drop) also take time when runtime begins. GetComponent is extremely fast (especially when you know it won't fail), almost as fast as that time taken by serialized references
To worry about that as being "inefficient" is an extreme micro-optimization AT BEST, and a waste of time normally
Worry about stuff that you do many times
GetComponent in Start on something that there's only one copy of is completely fine
GetComponent in Update in something you've got 500 copies of is...less so
would a simple distance check be good enough to check whether an AI Agent has reached its destination?
only asking because ive seen people say you need to do some random complicated stuff to be accurate
its probably not complicated but its this,
its not complicated now i look at it properly haha
you know, this is something I've needed to figure out myself. i have really inconsistent logic for "are we there yet?" in my game
I just call it once I'm within the stopping distance
lol fair enough, thats what i was planning
Ah, it finally works now. Thanks guys!
not particularly sure whats going on here hes just spazzing out everytime he finds himself a new patrol point to go to
maybe hes still in that 1 unit range of the distance check and its spamming? idk
Log each time that you set a new destination
If I have a component on a game object that implements an interface, can I use getComponent with that interface passed in to get it? Or does it have to reference the actual class name?
or maybe just use Debug.DrawLine to draw a line to the destination
Yep!
Ah!
Any type that the component can be assigned to will work
that could be huge for what I'm facing right now
basically rewriting everything I've done from the ground up it's such a mess
(well, except for System.Object, maybe...)
I want to set the startgame function to this button but it aint appearing
You've dragged the script asset in
You need to drag in an actual object in the scene
wdym
MonoScript is how Unity represents the actual script asset -- the .cs file
Have you added the mainmenu component to an object in your scene?
yes to the main camera
Drag the main camera object in, then
bruh , thanks 😂
Hey I'm having some trouble with a script I wrote to slowly pan the character from any y rotation to a certain one. I set up some Debug.Log statements and the console says that it called the function without error, yet the function did not print that it executed. Any advice would be great. Thanks!
viewControls.SlowTurn();
Debug.Log("Called slow turn");
public IEnumerator SlowTurn()
{
Debug.Log("Slow turn executing...");
Quaternion targetRotation = Quaternion.Euler(0, 308.55f, 0);
Debug.Log("Target rotation: " + targetRotation);
while (Quaternion.Angle(transform.rotation, targetRotation) > 0.01f)
{
float step = turnSpeed * Time.deltaTime;
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, step);
yield return null;
}
Debug.Log("Slow turn completed.");
}```
you aren't starting the coroutine correctly, use StartCoroutine to start it, calling the method normally just makes it run to the first yield
StartCoroutine(viewControls.SlowTurn())
Thank you. I will try that
actually, it doesn't run at all! I thought that was the case at first
StartCoroutine does immediately call MoveNext on it
so it looks like it runs to the first yield
that worked perfectly. thank you for your help
it should run to the first yield when called as a regular method, but since nothing would call MoveNext on it then it doesn't get past that first yield. if it didn't run to the first yield then their logs wouldn't have worked at all
they log "Called slow turn" after calling SlowTurn()
huh, TIL. seems it's a common misconception about how methods that return IEnumerator work, but you're absolutely right it won't actually do anything until MoveNext is called
https://dotnetfiddle.net/ZS2dYB
you wont regret it
I swear I tested this once and had the enumerator hit two yield statements in one frame (once when the method ran and once when Unity called MoveNext on its coroutines)
but, no, that wasn't the case
im turning off gravity on my player
and how do i make him not be affected by other objects falling
like the y position
without freezing the y position
if an object falls on his head for example
pretty much i dont want other forces of other objects acting on my player
without making it kinematic
You could try assigning to the velocity every fixed update to keep the value what you want it to be, except I believe objects will still move you slightly due to depenetration
why? this would do exactly what you want it to do, you just wouldn't be able to move it along the Y axis using physics
Overriding the velocity is the only other way, but that may be difficult . . .
Some irregular movement will occur if multiple objects keep hitting it . . .
i spent the last 7 hours trying to figure out swimming
like just the bit of getting into it
and out
that isn't really an explanation of why you want to not freeze the Y axis
whys the walking animation not playing
heres the code for the playermovement https://hastebin.com/share/ayevidebuc.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i feel like making it kinematic would be a good solution. any reason why you are avoiding that?
This is a really simple shader question, though technically not a programming issue the other channels have not been helpful. So, this is textmeshpro appearance after changing the stencil settings to
Ref 1
Comp Greater
Pass Replace
then i added (second picture) if (c.a == 0) discard; in the pixel shader, however its pretty choppy, i think due to the anti aliasing being applied on per character basis? i dont know how to get good blending here. i've been trying for weeks but i think it's a simple solution.
you don't have a paramter called walk. remember spelling matters, including capitalization
I think the problem is the stencil settings skipping any pixel which has already been set, but i think i have to have some sort of alpha threshold:(
shader questions should go in #archived-shaders
how do I check what the current scene is?
What have you tried? That is answered from a
search . . .
bro thanks it did work
oop im dumb, forgot to do that
sorry
Searching is always the first thing to do . . .
just a question its a bit delayed when it finishes walking
even tho i have got exit time off
It's probably based on the animation transition settings . . .
ill take a look thank you
will this have any effect on my game
you may end up with some issues where you think you are using one when you're really using the other in the code. so it's usually best to use a different name
No, it's a warning (yellow), stating your custom class has the same name as a Unity class . . .
will i be able to build the game with this warning
(right now I am only using my charactercontroller)
Only one way to find out. Give it a try . . .
A warning and an error are not the same thing . . .
because I'm getting this weird error and I don't know why (when trying to build)
here i have a new player movement script is there anyway i can make it so the player move not whatever im moving with rn?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
This is a warning. Not an error.
yeah but it doesn't build anything
the build fails
Are there actual errors when it fails?
but i dont know what these are
and before i ignored them because they did not affect the game
i fixed it
okay so i have two enemies each one with a different movement script since i want to change it a bit, my problem is that if i write a public gameobject called player (so they know which element to move towards) on both of them it gives me an error, i´ve tried to do both of the gameobjects private but it still gives me the error
what am i missing?
okay i solutioned it
since i was literally doing copy paste for the base of the script i also replaced this so it had the same name as the other one
what a smart fella that i am (im not)
public void MoveListEntry(List<Type> _list, Type _type, int _oldIndex, int _newIndex)
{
Type _listEntry = _list[_oldIndex];
_list.RemoveAt(_oldIndex);
_list.Insert(_newIndex, _listEntry);
}
Will this work for what I'm trying to use it for? (Moving an entry from a list provided from one index to another)
below is a regular TMP text added to the scene on a screen space canvas, above is the same exact tmp text but rendered to render texture and shown in a raw image, why so different?
why is there a saturated blue on the text in the render texture, when its supposed to be plain white
can i use floats and ints to validate a while loop?
== not =
true
And remove the float
Then declare it somewhere
Not inside the while condition
But yeah, of course you can use floats and ints for conditions
Same as an if statement or any conditional
okay and this is more a math question than coding i think but i have a form of calculating the angle towards the game object that i want it to follow
and i want to make the enemy stop once it reaches x amount of distance
since im not calculating the distance but rather the angle i need to calculate the distance
but i forgot how to do that :/
Vector2.Distance
This is 2d I guess, right?
yep
so vector2.Distance and then i write this: (player.transform.position.x - transform.position.x, player.transform.position.y - transform.position.y)
Or just player.transform.position - transform.position
makes sense
distance is a 1 variable thing right?
not x and y
only the distance
as for example
distance = p
p = 15.6
Distance returns a single float
I don't mean to pester, but I'm still lookinng into documentation, trying to figure out if I'm using all these bits correctly.
right now im creating all my data in a static class with static readonly dictionaries, is this a fine way to do it?
for example, all the tiers for each stat along with its weight, etc that can roll on an item
Remove new- ah as umbra said
and then i write again player.transform.position - transform.position right?
just remove "new"
Exactly the same, without the new, as long as distance is a float
I'm not sure what I'm doing wrong here. it's asking for a List and a Type, and I tried two different ways to provide it, but it's throwing errors for both. I'm not sure what it wants here.
How do I improve my code architecture
typeof()
if i write it afterwards again it works
if not it gives me an error
you trying to make it so you can swap between two different inventories?
!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.
did you read the error?
Distance takes 2 params. Check the docs.
yes
Oh, missed that minus sign
All I want to do is take an item in an inventory, and move it to a new location within the same inventory.
okay so then what do you think you should do?
OH
yeah this gives me all of it
then just swap the indicies?
Why
and then it compares the distance between transform.position and player.transform.position
Because don't send screenshots of code 🤷♂️
That is the standard here
Your screenshot was awful lol
or atleast i think so
@covert sinew https://gdl.space/rahudoboqo.cs this is my code for my game if you wanna reference it
Correct
using #region and #endregion might make it easier to read. as well as using comments
if you hover over the function it tells you the parameters it needs
sorry, didnt see that you had the minus
cuz my dumb ahh forgot the minus
i’m assuming your question was how to make it more readable
Maybe pastebin
Thanks
Sure, that is kinda not a great one though. The bot showed 5 sites that are better
since i just copy and pasted what i had before i had to write it again (i didnt have to i had to remove the minus) so that it has 2 Vector2
gdl.space is super good
i used it once and it worked pretty well
i think my personal fav is paste.ofcode
i like being able to select the language
Pretty sure ALL the ones the bot listed can do that
oh word? i think i just started with gdl.space and then did paste.ofcode. i must have missed it on the first one
i think i also favored the second because i could edit it after creating a link. i remember being unable (or just missing how) with the first one
Isn't it easier to see all code while you on your phone with a screenshot
its not the practice here even if it were
anyone have any suggestions? or is this fine
its disruptive just sending screenies
I'm on my phone. And no, not even a little lmfao
It is SOOOO much worse
Can barely read any of it
i love the three people reacting no that haven’t even mentioned anything
i’ll make it five
idk what i did but my game explodes whenever i start it
i think i messed up big time
kewk
do it return any error messages?
i'd guess infinite loop
i agree. i’ve only ran into that issue when i messed up a loop somewhere
yep, infinite loop because you never change the value of distance
but also why is that a loop
oh so i have to write the formula inside the loop
you need to update distance for it to stop looping. but also why have it as a loop? would an if statement not suffice?
i guess so
Just put it in your update function, there's rarely a usecase for while loops during runtime.
Make while an if
Esit: ah, lag, that was suggested
Unless you're generating something. But for gameplay logic like this, your update function is yourloop.
thats a good way of explaining that
i just learnt about while like 3 hours ago so i wanted to try but yeah totally right
an if works
Any bit of code needs to finish before any other bit can. So the ENTIRE while loop needs to complete before anything can move, and if nothing can move, the while loop can never continue
ohi wanted to paste a gif :((
Please do not do that
maybe you could try looking up when a while loop would be a good tool. then you’ll have an idea of how to experiment with it
so whenever i use it i should make the variable that validates the loop change inside the while
sure will do!
tyall!
Basically yeah. You can use coroutines to yield the main thread too though
whys the car pink lol
Beacuse you're using a shader that isn't compatible with your chosen pipeline.
Or you're using a shader that has an error in it.
how do i change that shader
Also, not a coding question.
i didnt know where else to put it lol
You can ask basic Unity questions in #💻┃unity-talk , or in this particular case #🔀┃art-asset-workflow , pick one.
But you'd do well watching a basic tutorial on how materials in Unity work.
done
is there a yt video for that?
I can't imagine a world where something basic like that isn't covered in some video, yeah
Given that beginner tutorial series are the majority of what make up Youtube/Unity videos
I feel like most of coding is functions, variables and class, if Statements and loops. I feel like I can create my entire program with these but I see people using events, lambda, return keyword, switch Statements functions and a couple of other concepts. When do you need these other concepts?
So, Im using a distance joint for my grappling hook, whats the best way to figure out what direction the player is traveling in for when I break the grapple? (2d btw)
When you want a higher level of abstraction.
Which is programming all about.
i mean, the return keyword is pretty fundamental...
I guess you could completely replace it with the out keyword
You could write a game by just typing 1 and 0 in a text file and saving it as an exe if you really wanted, but no one does that for some reason.
C# allows you to treat functions like any other object (hence delegate types)
this enables higher-order programming, where you compose functions together to get more complex behavior
That's a bit extreme example
Thanks
Yeah, but it conveys the point: the things that you mentioned are there to help you write better projects more efficiently, not to impede your progress.
by "switch statement functions" do you mean something like this?
public float GetSomething => mode switch {
Mode.Off => 0f,
Mode.On => 1f,
Mode.Broken => -1f
};
because that's a switch expression
When I see => it hurts my brain
I mean, events are super powerful and important. They can be used all the time
Yes
in this case, it's just expression body syntax and isn't really anything super complicated
oh, huh, that's new...
If you look at most beginner stuff. You never see that
only the low quality beginner stuff
Most beginner stuff is written poorly 🤷♂️
Writing like that makes things tough when you want more complex systems
it's a nice way to write methods and properties that fit into a single expresison
public override bool CanEnterState => base.CanEnterState && CanEnterWithTarget(candidateTarget);
public override bool CanEnterState => base.CanEnterState && Vector3.Distance(interactor.InteractPoint.position, interactable.TargetTransform.position) <= range;
on the ragged edge of "line too long"
Jumping from that beginner level to more advanced I find difficult
hi
Just takes time and effort
AETHONOSITY
Practice, and wanting it
HI
Hi
well that's not a code question. but #💻┃unity-talk message
Active ragdoll fighting
no
i cant 😦
make a top down view game where you are a shark and you have to eat people to gain points
good starter idea imo
Here's what I've finally come up with, after working on it for a long while. Thoughts on this?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
My inventory system doesn't have set slots, but creates and destroys them as needed, so it needed something more complex than what you provided.
where is the navigation tab in unity so i can bake like the walkable areas?
You can add it via the windows menu. If you're on a recent version, it moved to the navmesh surface component though
Why can't you just add a variable? This doesn't work: cs void Update() { cooldownClock + Time.deltaTime; }
But this works? cs void Update() { cooldownClock = cooldownClock + Time.deltaTime; }
Can someone explain why this is the case, please?
What happens to the result of just adding it?
Are you talking about this situation? cs void Update() { cooldownClock + Time.deltaTime; }
Yes
It gives an error.
I know
Also, if anyone has the time, It'd be helpful if someone with experience could review this, and tell me if my code here is adequate or psychotic, I'd be in your eternal debt.
(18 to 327 are the areas in question where I worked on today)
I am asking what SHOULD happen in that case
The variable will have Time.deltaTime added to it.
Then use +=
But just adding them, the compiler wouldn't know what to set the result to.
Assignments use =
Think it through, and that will explain why you can't
void Update() {
cooldownClock += Time.deltaTime;
}
Can you explain the differences between += and =+? I think this is what I am not getting
One is valid code and the other is not?
Both work, but are they different?
Oh suprising. Well, then no, I would assume they are not different
I thought =+ was a syntax error. Interesting
All I was saying is that THIS makes no sense, because there is no = sign
void Update() {
cooldownClock + Time.deltaTime;
}
So the parser isn't trying to assign something
Okay, thank you for the help!
You COULD make a language that does it, or perhaps overload the + operator, but it is just not default in c#
That is just an arbtrary choice by microsoft
the way of calling another script was creating a public class inside the script i wanted to call the other with right?
Not sure what you mean
lemme try to show it
You do NOT need to have the classes in the same file to call them
In fact, they should NOT be in the same file
Im making the camera shake on my virtual camera when the player moves right or left for a bit with this coroutine ```private IEnumerator CameraShake(string direction)
{
if(direction == "Right")
{
while(true)
{
Debug.Log("woking");
VC.m_Lens.Dutch += 1;
yield return new WaitForSeconds(0.01f);
if(VC.m_Lens.Dutch == 10)
{
break;
}
}
while(true)
{
VC.m_Lens.Dutch -= 1;
yield return new WaitForSeconds(0.01f);
if (VC.m_Lens.Dutch == 0)
{
break;
}
}
}
if(direction == "Left")
{
while (true)
{
VC.m_Lens.Dutch -= 1;
yield return new WaitForSeconds(0.01f);
if (VC.m_Lens.Dutch == -10)
{
break;
}
}
while (true)
{
VC.m_Lens.Dutch += 1;
yield return new WaitForSeconds(0.01f);
if (VC.m_Lens.Dutch == 0)
{
break;
}
}
}
}```
the problem is because its a coroutine if i move right or left too quickly the while loops dont run properly because the "dutch value" is reaching the set point for it to break. how would i go about fixing this
okay wait lemme reword it
@teal viper
In the code, I actually explain what everything in it does in excruciating detail through comments.
how can i call a function inside script b while im inside script a
It's my personal preference to overexplain my code in comments, since I have a habit of forgetting how programming works, and how I did things, and what the hell my code is doing.
I don't need excruciating details. Just an overview to know what I'm gonna read about.
public MyClassName scriptA
scriptA.MyFunction()
my brother is just another me fr
ty ill check that out
It's an Inventory System which uses Lists of Inventory Objects, spawning and deleting inventory slots as needed to hold everything in it, rather than having discrete slots
Today, I completed the following functions:
Add Items
Add Items to Specific Slots
Remove Items (of type)
Remove Items from specific Slots (of optional required type)
Move Items (the most complex piece, which can handle stack splitting and merging and all that jazz)
Waiting for a specific value like .01 is probably not gonna work well, depending on the framerate, there might be +-0.01 difference or even more.
Okay. Sharing the code would also be useful.
but im using that wait for seconds to make my while loop go slower so it looks smoother in the transition for the camera shake
I did
It's up above there.
Ah, you shared it previously. Didn't notice.
I'd suggest waiting for the next frame and then do logic according to the time passed.
I dont know how that would fix it tho because if the player is pressing move faster than the camera is completing its shake cycle it will just break every time
It looks fine aside from maybe I wouldn't make it an SO. Also, what you call an override is actually an overload. Method override is when you override a method from a base class.
I mostly made it a Scriptable Object so I can easily use a unity plugin that allows me to save scriptable objects without converting to structs, since I'm going to need massively complex save files, and I would get lost in the weeds if I had to manually set all of that up myself, and also so I can have multiple inventories easily and handle them all.
whats the purpose of doing it this way?
also SO's work well for an inventory, im doing the same thing
I have a scrolling inventory, so it can't have finite slots, and I think it looks sexy to have items "loose" in your inventory.
You can save plain classes as easily. You don't need structs.
And you can have as many inventories as you want. I don't see how SO is helping with that.
so an infinite inventory?
you still need to define specific slots, I don't understand how that works out
Might be helpful if you provide a video showing the issue, as it's not entirely clear what it is.
It's been over a year since I last worked on my save and load system, but it nearly broke me, man. Saving and loading an inventory, from everything I researched on the matter, was a terrifying tarpit of insanely complex data structures, that had to be convverted to and from one another in ways I simply am not a good enough coder to understand.
Using SO's is absolutely easier than trying to save and load Classes directly. Like, I'd say at least 50% easier.
A save and load inventory system is what very nearly made me quit game development, and was so frustrating that upon finishing it, I had a 9 month hiatus, just in sheer catharsis.
Using an SO changes absolutely nothing about how it's saved. You're still limited to serializable data.
It's easier to add items to it, since Lists are more friendly than arrays.
I have a plugin that makes SO's serializable, is the thing.
I just directly serialize/deserialize the SO
They are serializable by default though
No they aren't.
If they weren't, you wouldn't be able to create instances of it in the editor.
Last time I worked on it, SO's were explicitlly not fully compatable with saving to JSON, yeah
I believe im making a game very similar to him and have solved this issue myself
They are.
the only reason I use SO's for inventories is to be able to easily plug it in to anything
instead of holding a reference singleton or whatever
When did this change?
Never.
You probably misunderstood something about serialization.
dlich you are misunderstanding him i believe, you cannot directly serialize an SO to Json
nine months ago, I had to install a specific plugin to Serialize SO to JsON
you would have to serialize the data in it and then rebuild it
They were NOT serializable to JSON.
Of course you can.
what does an instance of an object mean?
i've tried, you can't
Not without a plugin, last time I was working on gamedev.
thats why I made my own save system
Yeah. I took the other angle, and just used a plugin that MAKES them serializable to json
@covert sinew you two should check JsonUtility documentation. It plainly states that SOs can be serialized
Is this an excessive amount of assembly definintions or nah
It means that your reference doesn't point to anything. Do you understand the concept of objects and instances in C#?
Not unless there is a problem with it?
It does sounds unnecessary and clunky, but nothing beyond that.
this is what happens when I try to serialize an SO using JsonConvert
nothing was saved
What's JsonConvert?
and i should reference from the other script around?
the newtonsoft json utility
You should use JsonUtility which is the native unity way to convert an object to a json.
You should first find out what throws the error. For that you need to read it.
the line 40 (the first image)
What line throws?
doesn't work, also newtonsoft is now built into unity
Okay, what are the references on that line?
https://github.com/applejag/Newtonsoft.Json-for-Unity it is this btw
Newtonsoft.Json (Json.NET) 10.0.3, 11.0.2, 12.0.3, & 13.0.1 for Unity IL2CPP builds, available via Unity Package Manager - applejag/Newtonsoft.Json-for-Unity
It does lol
this isn't even the unity one is it
its in unity's package manager
i want to check if the bool shooting in the other script is false or true
That doesn't answer my question. What are the reference type object on that line?
yes ik
why are you serializing the SO anyway ?
srry im not english native so i dont know exactly what you mean by reference type
Please read the documentation that I mentioned.
generally they are not meant for mutable data so not sure why you'd serialize that instead of a mutable poco on the SO itself @native seal
Google C# reference types vs value types. And come back when you can answer my question
alright
If it works for you, it's fine. Just make sure the asmdefs have the correct assembly references . . .
that's what I do
the reason I use an SO for the inventory is just ease of use
being able to plug it into anything
Imo You should not be using it for mutable data
You usually want to be able to create new inventories at runtime and pass them around. Having them as SO brings a lot of garbage that you don't need with it.
does anyone have a good free tutorial series or course on learning C# for unity?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
yeah but that focuses on overall? is there one that focuses primarly on just programming?
yes I agree that would be the one limitation
a value type is stored in a stack* while a reference type stores the direction of other stack?
heap vs stack
Did you look on the site for the programming tutorials?
oh does it have some?
yes the c# one pinned in this channel
okay so now i should look what a heap is
The second part of that sentence doesn't make sense. You don't have to understand about the stack and the heap for now. Just learn what types are reference types and what value types and how to differentiate them.
ah okay sorry thanks
Yes, that's why they sent you the link. Click on it and search for the tutorials you want . . .
ok cool thanks
basically what i understood is that whatever is a int, bool, float etc is a value type and class string arrays are reference
so answering your question im not doing any reference
right?
and thats the problem
Then you wouldn't get the error.
Go through all the identifiers(variables) on that line write down their types.
Names of variables
and its value type
value types cannot be null by default
Also, a value type in not stored on a stack. That's a misleading conception . . .
Break down all the keywords and write down what they are.
im also refering to the class multiShootEnemyShooting
Bingo . . .
and a class is a reference type?
c# generally abstracts all the stack/heap stuff
Yes
it was what the guy in the video explained
okay let me read the error now
It's a reference to an object.
you don't have an instance in your declared variabe
Do you know what a null is?
nope
so you cannot use something thats missing/doesnt exist
Do you know what a reference is?
imagine your program recieving a blank blueprint with nothing built yet
making an instance of an object "builds" that blueprint
a class definition is just a blueprint
the name of the variables?
No. Did you learn anything about object oriented programming yet?
nope
Well, then you probably should go over it first. It's crucial to understand to be able to work with C# and many other languages.
i know so little (type of variables, how to mess a bit with objects components, loops, switch and i think if counts as a loop but basically thats all)
digital post your full code in gdl.space
omw
you need to expand on your fundamentals
I'd recommend learning the mentioned things before proceeding.
Spoon-feeding them isn't a great idea.
why? it's one way to learn
thats what im going for
then they can reference the solution and figure out what went wrong
It's one way to learn one specific thing and have a broken understanding of the whole thing.
b4 yesterday i had no clue how to use loops or switchs
the microsoft docs has everything you need
digital do you understand the concept of classes
also im not "spoon-feeding" the answer, I want to see what was going wrong
a class is like the script?
A class is a Type . . .
a reference type ?
It happens to be a reference type, yes.
for example, a Vector3 is a type
i doubt he's going to understand that if he doesn't understand basic loops
i dont know how to read all that
its all very much in english words.
Value types are only stored on the stack when declared as a local variable or a method parameter . . .
i understand that i can somewhat ignore all the system. and whatever remains takes part of either reference/value type
i dont know what a stack is ( i have the thought that it is like a place where it holds information about something)
dont worry about that now
imagine that value types typically hold very basic data (including primitive types such as character, int, etc), reference types typically hold more complex data such as your class
Somewhat. You can worry about that later . . .
Ehh You could say Quaternion is quite Complex and is a struct
i saw a video and i understood something like (numbers and bool is value type) and (fancy things with strange words are reference (arrays, class, strings))
is there a way to reference objects without having them be included as a reference in a script or be part of a trigger? trying to put together a sort of tile lighting system
in c#, when you pass a "value" type into a function, anything done to it will not change the variable outside the scope of that function, this is not true for reference types since you are passing the same "pointer" that points to the reference type
That's a "special" case . . .
tile lighting ?
in fancy Unity fashion
pretty much something like this https://static.wikia.nocookie.net/baldis-basics-in-education-and-learning/images/8/85/Custom_lighting_teaser.gif
okay give me like 5 minutes to understand this because it has a lot of words that arent popular in my mind
why would you not store the references ?
what do you mean with passing a value type into a function? using a value type inside a function?
i was thinking about making a tile lighting object that would affect objects around it in a certain range as opposed to giving each individual tile the same script
to simplify it, just remember that when you pass a value type, you are copying it into the function and the function has no knowledge about it outside of that function. A reference is like giving the function an "address" of your type that it can go to and modify
just put the tiles in a List/Array. then iterate through them
like myFunction(int num), the parameter num which is an int is passed into the function
They still don't understand the concept of types and instances I think. They won't be able to understand that explanation.
You must have a reference to the objects in order to act on them. Assign the references on the current script, a different script, or find/search for them during runtime (slow) . . .
compared to myFunction(myClass class)
the "address" of your class is passed into the function
the function can then go and modify it directly
while an int, a value type, is just copied over
but i dont want to modify something from outside the function i just want to check if the bool is true or not
maybe im mixing things up
im explaining the general difference between value types and reference types
when your program asks for "multiShotEnemyShooting.shooting" it looks for the address and cant find anything
You're going off-topic about what they need to learn/figure out. The goal was understanding a reference type so they can find the reference variable to understand a null reference error . . .
You want to access the bool that is on some specific object. To be able to do that, you need a reference to that object. You can't access something in something that doesn't exist.
im explaining the fundamental difference between value types and reference types
so i need to create a var gameobject with the item that holds the script inside on it?
a value type can never have a null refereence because the value is the thing itself
not a pointer to something
since your script is a monobehavior, you need to populate "public MultiShotEnemyShootingScript multiShotEnemyShooting;" on your gameobject
No. You already have a reference, but it's not pointing to anything.
populate?
I'd suggest googling Object oriented programming and understand that concept first.
when you declare public MultiShotEnemyShootingScript multiShotEnemyShooting at the top of your script, you are promising to give it a built "object" that follows the blueprint of your type MultiShotEnemyShootingScript
You have a reference variable but it is not assigned a value . . .
if you don't fulfill that promise, you will get that error
either drag that script into that slot in the inspector, or get the component in void Start
by using GetComponent
assuming your other script is also a monobehavior
oh so i need to write GetComponent(and then localize the script)?
what do you mean localize?
lemme show you (my keyboard doenst have the > and the other way around symbols so i cant write the exact thing here)
rb2dEnemy = GetComponent<Rigidbody2D>();
smth like this
yes
yes, assuming your script is a monobehavior that is also on the same gameobject
yep
you did the same thing when getting the player
player = GameObject.FindGameObjectWithTag("Player");
it also gets a reference to the player gameobject
if it werent i would have to create a gameobject , and then search inside the gameobject components for the script?
no, not necessarily, it depends on how you made your class
more than create a gameobject creating a variable that is a gameobject
and what functions it serves
what is the difference between monobehaviour and whatever else types there are?
monobehavior is a class that unity has made that your class can inherit from
research more into object oriented programming to understand inheritance
If you answer the next question, you would be able to solve your issue easily:
What is multiShotEnemyShooting and does it exist on line 40?
in simple terms, inheriting monohevaior allows you to place the script onto a gameobject and use the premade functions Start and Update
multiShotEnemyShooting should be the script that i need and it doesnt exist since i didnt reference it (either by GetComponent or dragging it around)
i think
That's correct. So do you understand how to solve it now?
Check the tutorial again and see where they assign it.
if multiShotEnemyShooting wasn't a monobehavior, you would create a new one by using the "new" keyword
what tutorial?
okay
Was it not a tutorial code?
nope im writting on my own
however, your class needs a constructor so that the program knows how to fill in the variables in your class
if you were to use "new"
messing with things here and there and trying to get problems so i can learn
make a game inside C# console application, You'll be a c# chad in no time
not the best way of learning but each day i assign myself something new to learn and to try and give an use to it
Ok well, I really suggest you go and learn the basics, starting with OOP. Because you're risking being ignored by people here in the future. At least by people that support proper learning methods.
appreciate it
OOP?
KEWK
i dont believe telling a beginner read the documentation is the best solution
Object oriented programming. Something I mentioned numerous times in the last hour
learning how to read documentation should be one of the first things to learn as beginner..
yes, but when he doesn't understand loops, i don't think it would help
It depends. There are appropriate materials. If you don't understand OOP, it's too early to read the documentation too.
who carees about loops, they barely know what an object is
docs are straight up confusing since sometimes you get no context of things and use fancy words that with my current level i cant understand
sure
lookup words you don't understand
be VERY warey of unity tutorials please
the docs has a list of all the keywords used in c#
its not just the words
what is warey?
cautious
i dont watch them
Where did anyone say to read the documentation? They mentioned learning c# basics as that is necessary to start with the Unity basics of programming . . .
i watch tutorials of c#
someone else linked the documentation
The microsoft site isn't just "docs"
its like the docs but explained by someone
they are learning lessons
yes very good
they have videos too
its in spanish but basically this is what i watch https://youtu.be/BFJU--8yqT8?si=JLUxPAf19eCt4-ub
Para descargar los cursos totalmente gratis visita nuestra pagina:
http://www.learnwtutorials.comlu.com/
Siguenos en:
facebook: https://www.facebook.com/learnwtutorials
twitter: https://twitter.com/LearnWtutorials
learnwtutorials
aprende
programacion
tutorial
videos
lenguaje de programacion
computadora
tecnologia
those types of videos
i dont like unity tutorials
since they just give you the solution and usually dont explain anything at all
learning c# through unity is more diffcult
that isn't even the problem
unity tutorials give very bad architecture advice, such as making every field public
i recommend not doing that
a field should default to private and only be public if theres a very specific reason for it to be public
i tend to write public if i want it to be changeable from other places or private if i only want to mess up with it from inside the script
Oh, you meant the c# docs, not the Unity one. That's different. They provide definitions and (sometimes) examples of the term in use. They have to figure out what it means from somewhere . . .
yes i realized that like i said
it is generally better to make it private and only allow changes through a public function
since you will be able to put restrictions on it and whatever other logic you want associated with changing that variable
so making everything private and whenever i want to change a variable make a public function that manipulates it specifically?
yes
if your class is a monobehavior, you can add [SerializeField] before your variable to allow it to still be changed in the inspector
it is very useful
they should be [SerializeField] private instead
i usually write public and once i know i dont want to use them in other place change it to private
90% of my variables are private
that will take out possible problems from the equation right?
This is what most beginners do until you learn about properties, methods, and encapsulation. You'll begin to use the correct access modifier and decide whether a field should be a property or variable . . .
i had a deja vu of this
but when you scale things, you will have problems
havent you told me this b4?
if 20 things are changing your public variable
yeah instead of 20 things changing a variable its better to have 20 things call a function that changes that variable
didnt think about it but it makes sense
yes, since you can add whatever other logic in that function to restrict those other 20 things trying to change it
for example, not allowing it to go below 0
or something like that
yeah
the same thing happend 3 days ago
i spend like 2 hours trying to understand something that i already knew
but since im a dumb ahh i forgot smth and just messed up
we all start somewhere
this should be it right?
yes, make sure that class is added as a component on your gameobject
it is
similar to rigidbody, which is just another class that unity has already made
i thought that was the issue b4
because i forgot to add it
yu should always opt in for a serialized field and drag n drop reference inside inspector instead
but i added it and it kept displaying so i came here asking if someone knew what was happening
either one is fine really, but since unity gives you the ability to drag and drop it cleans up code
i dont like that method since instantiating prefabs usually doesnt let you do that
prefabs are completely different
yep they are
nothing to do with that
Well you have GetComponent its better to do it since the components are already on the object
and yes Prefabs cannot reference scene objects
the enemies*
why ?
for following the player
for prefabs you generally get the references at start
Real.
if its a gameobject in your scene
no for prefabs you pass the dependency via whoever instantiates it
that works too
Everytime you spawn an enemy you're doing a Find
instead of getting the same reference from the thing that spawns it
hmmm i get what you are saying but idk how to execute that
Having [SerializeField] on a public variable is redundant. [SerializeField] allows a private field to appear in the inspector. If your field is public, by default, it'll appear from the inspector . . .
didnt know you could do that
yes i know but once im finished coding i replace everything with private
so im just left with the fields and messing around to find the number i want
Yep . . .
the object in the scene that spawns holds the reference to say the player, then once its stored on awake once every time you Instantiate you can pass player via a Method like "Init()" inside enemy that gets that reference
this has good example
https://unity.huh.how/references/prefabs-referencing-components
i didnt understand that i will check for some explanation in some c# video tho
oh
i guess i wont be needing a video
passing objects/data through methods should be one of the first basic concepts you should learn
you'll probably be doing it A LOT
yeah not just probably but nearly 90 % of my scripts have the walmart version of that
kewk
it looks intimidating at first but it gets simpler with time , just keep doing it and eventually "it sticks"
sure will
At least upgrade to the Target version . . .
how is that?
XD
no need to explain
i will learn it myself
but first i wanna finish with the new type of enemy
you know they meant Target the store not an actual method or function lol
AINT NO WAY
BHAHHAAHHAHAHAAHAHAH
srry im from spain
we dont have target nor walmart
amazing lol
omg im dumb
BHHAHAHAHAHAHA
target version
makes complete sense
since my problem has to do with targetting a gameobject i got confused asf
KEWK
this made my day
anyway imma go eat havent eaten in like 30 hours or so
ty for the help!
Oh, I figured you knew about Target since you mentioned Walmart . . . 😄 🤣
i know about target but my mind just ignored it 🤣
Hello! I'm remaking breakout in unity and I needed to save my highscore so when I restart the game, it saves the highscore. With what I have currently, the score and highscore count up at the same rate but I'm not really able to get it to save.
this is what I have and I know it's wrong but I'm not quite sure how to make it work either because I've tried all kinds of youtube tutorials
but my score is counting up in another script which is throwing me off
Pay close attention to the strings that you're using.
It would be better to assign the string in the field initializer or serialized field and use that variable everywhere else.
In order to avoid human errors.
Yeah.. what I'm doing is for an assignment and my teacher isn't expecting a serialized field. I just wanted for the highscore to save when I exit playmode. I reset my scorecount when i run out of lives so that I do manage to keep my highscore when I restart in the same play session
I just don't quite understand how I can save my highscore using the playerPrefs because that is what I saw in a lot of youtube vids about how to save highscores
Again, pay attention to the string that you use in start and in update.
And my suggestion is:
private string highscoreKey = "HighScore";
//When using player prefs:
PlayerPrefs.GetInt(highscoreKey);
What string are you using when getting and setting the value in player prefs? Is it the same string..?
it probably was, i just removed the strings and it works the same as it did before. i think i was referencing from another project but I ended up changing my values to static ints so that means I don't need the strings right?
What? No. I think you're misunderstanding
Share the script properly, so that I can copy paste it.
!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.
public class UIManager : MonoBehaviour
{
public TMP_Text scoreText;
public TMP_Text livesText;
public TMP_Text highScoreText;
public static int scoreCount;
public static int highScoreCount;
public Ball playerData;
public void Start()
{
if (PlayerPrefs.HasKey("HighScore"))
{
highScoreCount = PlayerPrefs.GetInt("HighScore");
}
}
public void Update()
{
if (scoreCount > highScoreCount)
{
highScoreCount = scoreCount;
PlayerPrefs.SetInt("Highscore", highScoreCount);
}
scoreText.text = "Score: " + scoreCount;
livesText.text = "Lives: " + playerData.lives.ToString();
highScoreText.text = "Highscore: " + highScoreCount;
}
}
I'd prefer if you shared it as Large Code Blocks, since I can't copy specific parts on mobile like that...
oh crap sorry! give me a sec.. thx for helping me
Nevermind, I did myself.
Does the string parameter here:
PlayerPrefs.HasKey("HighScore")
Equal to the string parameter here?
PlayerPrefs.SetInt("Highscore", highScoreCount);
```@timid badger
anybody know how i can get similar gun interpolation to this when looking around
ive searched up what type of easing it is (Elastic out ease)
but i cant figure out how to implement it into my code and everthing i try dosent work so i end up just resetting it back to this
public GameObject gunPos;
public Vector3 TargetRot;
TargetRot.x = Mathf.Lerp(TargetRot.x, gunPos.transform.localRotation.x -Input.GetAxis("Mouse Y"), 5 * Time.deltaTime);
TargetRot.y = Mathf.Lerp(TargetRot.y, gunPos.transform.localRotation.y + Input.GetAxis("Mouse X"), 5 * Time.deltaTime);
gunPos.transform.localRotation = Quaternion.Euler(TargetRot);```
i remember in my old game i accidentaly recreated it by like doubling the rotation on a second object but i dont remember how i did it
I am not quite sure how to check that but I'm guessing it doesn't or else the high score count would actually be holding that value after i start another play session. Sorry, I'm trying to figure that out but I'm still very new to unity and coding just in general
I wanna spawn a prefab in a random place (ive alr done that)
but i want to make it so if the random place is already occupied by a certain object with a certain tag
then it would choose another random place
how would I get a BoxCollider2D for the random place
oh they are equal to each other i think that is the problem, i went back to the video I was using and I think i'm seeing what to do
i mean, it really isnt possible since that place is a coordinate
not an area
overlap point nvm
You can check it by looking with your eyes
Do you see any difference between "HighScore" and "Highscore"?
there's a difference now but it's still not saving my score
wtf
public void Start()
{
if (PlayerPrefs.HasKey("HighScore"))
{
highScoreCount = PlayerPrefs.GetInt("HiScore");
}
}
No, the problem is that they're different. They must be the same obviously.
I only see Get and not SetInt https://docs.unity3d.com/ScriptReference/PlayerPrefs.SetInt.html
in my first block of code they are the same
Yes, but not when you save the value
consider using private static readonly string as your key not some string hardcoded into
this comment is the one that helped me
love you all
i can sleep tonight now
They are not the same. One had capital S in score, the other had lower case s.
Just in case it is not obvious yet: S and s are 2 completely different characters and are not equal to each other, thus HighScore is not equal to Highscore
yeah true my eyes are failing me, thank you for the help though
That's why you should save the string in a variable and use it everywhere instead of typing it manually.
i cant convert a Vector3 into a quaternion, how can i make it rotate ? here is my aproach and it didnt work
by using quaternion.euler to convert it, but your initial vector is wrong from the start. you are using quaternion values, these are not what u think they are. use the eulerAngles
what is an eulerAngles?
nvm imma check a video explaining it since it seems a dense topic
im not learning allat
xD
i´ve seen 3 videos of euler angles and one on quaternions and i dont understand a thing
You don't need to learn quaternions. You just need to know that they're different and shouldn't be messed with manually.
oh the guy said later that normally all that is made with a computer
usually you can just use lookat with projectiles because you're probably aiming at some target anyway
nope im making it spread in a clocksystem
each "2 hours direction " i want to shoot a bullet
Depends on what you tried to do. It could've been correct if you tried to rotate on the z axis.
i just want to rotate the z axis
but i want to rotate the z axis
https://docs.unity3d.com/Manual/QuaternionAndEulerRotationsInUnity.html
Also worth reading
"Rotate z axis" doesn't make any sense.
yeah srry
What are you trying to do actually?
i want to rotate him based on the z axis
We say "rotate around a x/y/z" axis"
AngleAxis rotates it around the axis you provide it so experiment with it
Imagine an axis as a line going through your object. You rotate it around that line
yes i know that
thats why i want to rotate around the z axis
Now the question is, is it the local z or the world z?
There's a Transform.RotateAround method that can rotate the object around any point/axis.
srry for the ping but in my case i dont care that a gimbal lock may occur right?
since the only axis that im using is the z
I think I did? Not like 'rotate', but assign an euler angle to z
it says i cant use "eulerAngles" for that
then i get the problem i had at the start
that was my first approach
but it tells me that i cant transform a vector3 into a quaternion
Should the bullet rotate or just spawn at desired angle?
spawn at a desired angle
Right.
Then what's the problem with (bullet, transform.position, Quaternion.Euler(0, 0, zRotation); ?
That's totally not what I mentioned
Yeah, in this context it could be correct.
that it wont let me use it
it gives me an error but its traduced poorly to spanish
Non-invocable member 'name' cannot be used like a method.
Is zRotation variable a float?
yep
It should be fine. We didn't know the desired rotation axis back then. At least I didn't see any mentions.
yeah but i checked the doc and it says that i can use eulerAngles too
Euler needs some using unity.System; ?
i dont think so
What exactly did it say?
Can you please show the code abd the error?
No. Euler is not even a type.
Nah, not error. The code
What they mean here is that you can assign a value to transform.eulerAngles.
so i should think of transform.eulerAngles as another variable?
and modify it outside ?
Variable or property, yes.
You can check the documentation for it and see that it's not a method.
Cause pretty sure
'''cs
Instantiate(bullet, transform.position, Quaternion.Euler(0, 0, zRotation);
'''
should work
Damn
if i remove the parentheses it tells me that i cant convert a vector3 into a quaternion
i readed the compile error
Ofc you cant.
Your zRotation should be
private float zRotation = 45f;
Can't read your thoughts... We do t know what you have...
its 60 but ig its the same
Then do it. I don't believe it gives error
Check the Instantiate docs. The third parameter should be a quaternion