#๐ปโcode-beginner
1 messages ยท Page 421 of 1
sounds like its probably ur loading stuff thats the culprit
it adds 10 to it
the second part just clamps it
trying to serialise a fixed point math library - why does it look like this?
What's the benefit of adding 10? ๐
probably just an example
Ah
This is examle code it just increases the x rotation by 10 degrees and the Clamp ensures it cannot go above 90 or below -90
we tend not to post exact code that ppl can copy and paste w/o giving it a look first
and figuring out the logic bit on their own
Will that stop it from ever being able to rotate out of that limit? I need it to be able to freely rotate
I stared at this a bit a while ago, but nothing stood out to me. I would think to try and pinpoint exactly where the doubling occurs. I think it would be easiest by throwing a breakpoint at the top of LoadData() and stepping through it with the debugger, inspecting the values and lengths for data.items, Container, etc. But you could also sprinkle more logs around
Just call a function if it's within the clamp "limit"
ffs. It's example code. you implement it how you want
Start walking through your load data method. You start by looping through data.items and setting the corresponding index of Container to that item. That seems like a potential place to load the wrong things. Try logging i, Container[i].Id and database.GetItem[Container[i].Id]. See what gets loaded.
I think asking what Clamp does is a pretty fair question considering you said "Clamp ensures it cannot go above 90 or below -90"
Implementing something that doesn't fit my use case would be pointless, asking a question is completely fair ๐
the logic above it runs...
afterwards it gets clamped
if its in the limit. (its good as it is)
if its above the limit it clamps it back down to the closest limit
if its below the limit it clamps it back up to the closests limit
.. then the rest of ur code also acts normal
There are docs, as you have been linked for simple 'what does this do' questions
๐๏ธ docs will be ur best friend..
every unity function will have a description.. and majority will even have an example snippet of code
That's fair ๐
I hope I'm not misunderstanding and I'm wondering if I can skip defining x & y & z in favour of just doing it once. But from all I've read I feel like this might work 
Again, rotation.x and so on are not what you think they are
I am loading the correct items. I mean the first correct items. If i add 3 then first 3 items get loaded correctly then on the 4th slot it loads the first of 3 item
I debugged if the container gets expanded somehow but in my load method its always the amount I set.
https://hatebin.com/muunvhuqsbI do not know if this is any help but this is my other script
Thats got initialize item method in it
you'll want to work w/ euler angles..
(those are the angles we're familiar w/)
what u have there is rotation.x tahts teh x component of a Quaternion..
quaternions are 4Dimensional..
the x is not the x u think it will be
Could LoadData() be getting called twice, for some reason? That would duplicate the items without increasing the container size
throw a debug first line of it and see how many times it logs
Add this log before you load your container:
Debug.Log($"Index {i} - setting container with ID {Container[i].Id} to {database.GetItem[Container[i].Id]}");
And then show me what it logs
okay a minute
I never thought about it i will check
Okay, and anything after that?
Would I want to replace arrow.transform.rotation.x with something like arrow.transform.rotation.eulerAngles.x or is that still 4D?
Its the other logs I got suggested
eulerAngles are the angles we're aware of 0 - 360.. soo no thats not the quaternion
if u debug transform.rotation.x and then debug transform.rotation.eulerAngles.x
Okay, so data.items.Count is 2. Meaning you're loading 2 things. How many elements does Container have?
you'll see a difference
In this example I had 2
Ah, arrow.transform.eulerAngles.x instead? I only ask here because it takes about 20 minutes to test each change I make
don't really try to understand Quaternions.. most people dont ๐
we're just aware of them.. and use eulers instead
Okay, so there's two things in it. Then you loop over it and call SpawnNewItem on each one. Part of that function adds the new item to the list
So each item in the list duplicates
yes I prefer the "it just works" part myself
that should print exactly whats in the X property of ur Rotation in the Transform ๐
magic ๐ช
Okay I have a base to start off of ๐
Ah nice catch ๐
SpawnNewItem adds a new InventoryData. Is that what you're saying? It adds 2 more while spawning and it can keep duplicating it if i have more slots?
The highlight is a bit tough to see but that's adding elements to the Container list
Yes I found that line
Well good find. Now how can I fix it T_T
I should be adding them to the container elsewhere
I can do that in AddItem after Spawning new item
But it will be the same no? Since im calling add item.
Well, first off, what even is Container? That's not a very descriptive name
What should this list be?
I feel bad for asking so many questions so this will be the last one, would this effectively work like a limit for the angle?
[System.Serializable]
public class InventoryData{
public int Id;
[JsonIgnore]public Item item;
public ItemType itemType;
public InventoryData(int _id, Item _item, ItemType _itemType)
{
Id = _id;
item = _item;
itemType = _itemType;
}
public InventoryData(){
}
}
Container is this. Where I hold my Save data
Container is a list or array of those you mean
In words, what is Container supposed to represent
what is the actual purpose of this data
not really a limit.. but it does work like u mentioned earlier (if arrows' x is less than 30 or less than -30) it'll run the code block
So that I can save item types and item ids that sit in my scriptable objects
No, but, like, what is Container. The name Container is not descriptive. What purpose is it meant to have
That should be all I need
altho.. u sure u want both conditionals to be less than?
b/c less than -30 is also less than 30
obviously lol
Its ItemData i believe
List of ItemData
Less than 30, more than -30, got it
well still 25 is less than 30 AND more than -30
for what purpose
๐ค
That would be fine no?
just making sure ur doing what u think ur doing
tell me what this variable is supposed to represent
I want it to trigger if it's inbetween 30 and -30 so if it were 25 that'd be good
!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.
then wouldnt it be.. less than 30 && greater than -30?
< 30 && > -30 ?
ahah, no worries.. we all make minor changes like that all the time
Well What I had in mind (and also after some research) I thought I could Make this Serializable data. Instead of Holding a list of my InventoryItem which are prefabs with ItemScriptable objects as public fields in it. I could Hold Id and ItemType to save and load in this container
why is say "install queud"
Hey guys i have a problem with this script: https://paste.ofcode.org/39CZBp5DMbEMzDp2GWPfA3U . Basically i want the movement to be following the rotation of the player, but for now the movement that the player does is "static" (it doesn't follow the rotation). Btw this script uses unity's new input system
Basically I knew I couldnt save InventoryItem prefabs in a file I made dis
{
}``` I think I got it
Kind of a muddled mess but so is all the other code in my DLL so that's no different
I'm not asking for code descriptions. I know that it is a list of ItemData. Using words, what value does the list Container represent? What is the reason you have a collection of this ItemData. What is it going to do
hey does somebody know if i can make a switch statement using ranges from for example 0 to 60?
per case*
i tried to multiply my _movementKey with this formula without success: _movementKeys = transform.right * _movementKeys.x + _movementKeys.y * transform.forward
yes with pattern matching
whats thatt?
I don't know if it's efficient exactly but I've done switch cases with 100s of different values and it worked fine, unless you're asking something else
I just took psychic damage
๐คฃ
I would imagine so
thank goodness for "search" functions
this looks like a lot of work bro
It was fine when there were only 4 things to look for, then teh game updated and added like 100 different items of the same type and I'm too lazy to look for a better method
Well I saw someone doing it this way since I had no prior experience with the saving and loading. I thought I should get this plain c# class and store my Ids and Types in it. Then load back from it really. I may not be understanding your exact question though.
why spend 60 mins making sth by hand if you can spend 6 hours automating it??
jesus...
I will never end up using it again, not a huge problem
is there a way to know when the animation ends ?, to like do attack animation and then return to idle animation ? (I'm using GetComponent<Animator>().Play("name of the animation") )
to do it like: .play("attack") then .play("idle")?
its also better to spend 6 hours on it, imagine needing to change something in there
yeah
No, you aren't. I'm trying to ask, in your game, what does the list Container mean
What should be in this list
What does it represent
Why did you make this list
What is it supposed to do for you
Having to change something sucks, which is why they all share 4 coroutines total ๐
I can just edit them and anything that calls it changes
i spent 3 hours automating an array for 2 points i could have added in like 30 seconds. its a gamejam project im never gonna touch again but it was worth it
I'm aware it's terrible
Help me extract data from it, data that will help me pull items from my database
what is the point of the data
what would your game fail to have if you just deleted the whole fucking list
I cant save and load
save and load what
the Inventory items
so... anyone has a solution for this?
Just the ids and types of the items.
I do not hold the Item itself in it because its a scriptable object
Okay, so it's a list of IDs that you can save, with the purpose being to pull up ScriptableObjects by ID later
Yes
And presumably there's a real inventory containing those ScriptableObjects in a different variable, and this one is only used when saving and loading
The real inventory is a scriptable object called database which holds my Item Scriptable objects. I believe you can call that Inventory no?
Is it your current inventory or is it a database
Because those seem like completely different things
Current inventory is when I add items in inventory (which is just a 4 slot of hotbar)
I think you're asking about why your player game object does not move relative to the direction it is facing when you apply input, is that correct?
Then I do the Container.Add(new InventoryData(database.GetId[item],item, item.itemType));
When I add items.
yyes
So I can store their ids and types
Okay, so, do you have a variable that holds the "real" items
or just the one that stores IDs
A prefab called InventoryItem which has InventoryItem script in it
Thats the item that gets instantiated
How is your current inventory on a prefab?
tried writing a custom property drawer, why does this happen?
Probably because something wasn't done right
#โ๏ธโeditor-extensions would probably be the place to ask this
Well It is not. I cannot store information that does not exist. That is why I tried to have a list of inventory items and wanted to add to it but I could not make any sense cos i cannot save monobehaviour stuff
Okay, so you do not have a "real" inventory variable anywhere?
Please excuse my ignorance but I cannot seem to place it in my head. What do you mean by Inventory variable.
I mean a variable containing a list of the actual item scriptable objects currently in your inventory
not the IDs
the actual items
does < or include the number or exclude it? and how is it with >?
< means "less than"
<= means "less than or equal to"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName ="Item Database", menuName ="Inventory System/Database")]
public class ItemDatabase : ScriptableObject, ISerializationCallbackReceiver
{
public Item[] items;
public Dictionary<Item, int> GetId = new Dictionary<Item, int>();
public Dictionary <int, Item> GetItem = new Dictionary<int, Item>();
public void OnAfterDeserialize()
{
for (int i = 0; i < items.Length; i++)
{
GetId.Add(items[i], i);
GetItem.Add(i , items[i]);
foreach (var item in GetId)
{
GetId.TryGetValue(items[i], out int Id);
Debug.Log(Id);
}
}
}
public void OnBeforeSerialize()
{
}
}
The only place I have Item[] is here
ok ty
Okay, so Item is the actual in-game representation of an item. The one that does things. And your whole system is to try to save and load that. Is that correct
using UnityEngine;
[CreateAssetMenu(menuName = "ScriptableObject /Item")]
public class Item : ScriptableObject
{
// public GameObject prefab;
public int id;
public Sprite image;
public ItemType itemType;
}
public enum ItemType{
Misc,
Key,
Weapon,
}
Yes all my items are based on this.
Okay, so, you should definitely have a List<Item> inventory somewhere that is the current actual inventory. Then you need a function that takes in a list of items and spits out a list of IDs, and another one that takes a list of IDs and gets the list of items
rb.velocity is in world-space. To apply your input relative to the player's orientation, one solution is to multiply the player's directional vectors (which are themselves in world-space) by your input:
_rb.velocity = _movementKeys.y * tranform.forward + _movementKeys.x * transform.right + _rb.velocity.y * Vector3.up;
Then you can save or load that list of IDs as a simple string of JSON or however else you want to serialize it
and just call those functions to convert between them
Once the items are loaded, you do not need to keep a list of them around
what do you call the f in 0.432f? identifier or something?
suffix ?
i know theres one for longs, L or whatever
All right. Thanks for bearing with me. It is a bit lot to take in at the moment but I will try.
Start by breaking the problem down. The two functions described are a good start - List<int> to List<Item> and List<Item> to List<int>
my question was about to be about the M. thanks!
Your database is good, that's already what it needs to be
You just need these functions somewhere. The database itself is a good place to put it
ItemsToIds and IdsToItems
In terms of language, it is a suffix. In terms of its purpose in coding, it is syntactic sugar for a cast
Ah okay. I will do that in my database then! Thanks again.
too afraid to ask and dumb enough to fail trying learning by tutorials, I feel stuck in some sort of loop that I can't escape, I'm not able to start developing by myself and can't do 1 single thing without watching a tutorial about how to, already 6 months of studying C# and Unity overall and I still don't know anything, started feeling like coding isn't my thing but at the same time I really really want to make some progress.
Watching all of you just answering each others questions and helping each other about things that I don't understand even though all the time I spent studying the engine, am I dumb? how do I start? I really could use some help.
Sorry for interrupting any important conversation about any topic, there's no need to answer, just looking for some tips or smth, thx.
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
I'm trying to manually serialise a class, and every time i try to set a value in the inspector it immediately sets it back to what it was before. why is this happening?
let's see some code
i'm using the SerialisationCallBackReciever and a custom property drawer.
public void OnBeforeSerialize()
{
// Convert m_rawValue to double for serialization
serialisedValue = m_rawValue / (double)Fix64Constants.ONE;
}
public void OnAfterDeserialize()
{
// Convert serializedValue back to m_rawValue
m_rawValue = (long)(serialisedValue * Fix64Constants.ONE);
}
welp we're out of my field of knowledge gonna leave this to someone else
appreciate your honesty
out of curiosity what benefit is there to doing this manually?
or is it just for fun?
Some people answering competently here have a decade+ experience. So donโt get discouraged if 6 months donโt yet quite seem to get you anywhere. However most of them will not have learned their stuff via tutorials since they can at best give you an overview of something but you will learn nothing from them, as you have discovered. The key is to learn the principles behind the craft (theory) while also trying to apply those to a project and skip all tutorials except for said overview. Use books, structured courses and challenges you make for yourself. You only learn if you figure out the solution yourself. Tutorials fundamentally cannot help with that.
tysm, appreciate
im using a custom datatype which isnt serialised by unity nicely so i have to make my own version
I think it's very important to build foundational knowledge prior to seeking out tutorials for specific features. It's hard to glean knowledge from solutions presented to you if you are unable to understand a decent portion of it - the bits which are ancillary to the actual feature.
I think one of the best skills to develop early on is the ability to perform research on your own, outside of a tutorial. Especially where it comes to learning to read and understand official documentation. And be willing to ask when you don't understand what the documentation is saying :) . Then, when you don't understand what someone has done in a solution or why they are doing it that way, you can spend time to research it. You'll grow in all respects for asking questions and hunting answers rather than accepting things at face value.
I guess in short, don't pressure yourself to rush through things or achieve a feature or integration in short order. Accept that they will take more time starting out, and use that time to explore along the way - poke and fiddle with things just to see what happens. I've always found that once I have a basic idea of what's going on, that sort of exploration becomes pretty engaging and elucidating...
Answering questions has always been a big part of my own learning process as well, but that may be subjective. The repetition of simpler problems drives points home in my head, and more complex questions force me to study and explore and try to understand things which I wouldn't have otherwise, often leading to interesting insights. And if I say something stupid or incorrect, someone is (usually) around to correct me and help right my misunderstanding or oversight.
My recommendations in summary: work through a structured C#/coding fundamentals course, the Unity Learn Junior Programmer Pathway, and find a community in which you're comfortable asking and answering questions. Aspire to get to a place where the scripting docs and format make sense.
I am in the same loop. I am also so slow to understand. I follow tutorials and try combining them into my own stuff. I get lost. I come here and ask questions. I do not get them most of the time. Just 30 minutes ago while digiholic was explaining stuff to me I wanted to go and hug my moma. But I guess progress is progress. Just gotta have something in mind and get to work.
I was working on a seperate project just to test something while original project was open on my other screen. It took me an hour to realize that I was actually changing the other projects code and expect things to work on my other project T_T
why doesnt it work? it should normally stop the spawning (and a few other scripts) when GameOver = true; but why doesnt it stop??? https://gdl.space/hatuwekexe.cs https://gdl.space/yipapefuco.cpp
What's suppoosed to stop it?
If GameOver is false when this object is first created, you start a repeating function
and nothing ever stops it
ok but why doesnt it stop the other processes like my camera controller? https://gdl.space/eqirabapay.cs
this is in update
The if condition only checks when that code runs. Update runs every frame. Awake runs once.
so should i put it in awake??
Do you want to check for it when the object is first created
or do you want to check for it every frame
every frame?
So, then Update is where it should be
Your first one was in Awake. This one is properly in Update
oh yeah ok this one is completely useless if i manage to disable the spawning lol
is this the reason why my spawnRate /= IncreaseMultiplier; doesnt change anything?
Are you using spawnRate anywhere
You're changing a value that is no longer used anywhere
InvokeRepeating has already ran
so yeah thats the reason?
Awake runs one time, when the object is first created
InvokeRepeating runs the given function with the given delay between them
https://gdl.space/vizesasozo.cs changed it does this work?
- https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
- You're still trying to start it one time in Awake
If you want it to loop, it's going to need an actual loop somewhere
so do i have to put the LaunchPrefab() into a for loop?
for example
Well, there's a specific kind of loop that runs for as long as a condition is true
And since you want this to repeat until a specific condition happens, that's probably a good starting point
while loop?
yes
If your while loop has a yield in it then it won't be infinite
finally i got something right๐ ๐
If your while loop doesn't have a yield statement then prepare for the application to crash.
well, only if it's an infinite loop
happened 2 times, lost 2 my progress 2 times. on one day.
still dont understand it where and how do i have this magic yield
When do you want to wait
Remember, code runs one line at a time
Yield tells a coroutine to wait for however long before resuming
does this work pls tell me it works
{
while(projectile.GameOver == false)
{
LaunchPrefab();
}
}
IEnumerator LaunchPrefab()
{
yield return new WaitForSeconds(Random.Range(spawnRate - 4, spawnRate + 4));
Instantiate(projectilePrefab, transform.position, Quaternion.Euler(0, 0, 0));
spawnRate /= IncreaseMultiplier;
}
Remember, code runs one line at a time
Awake happens, checks the condition
enters the while loop
and then calls LaunchPrefab
and then calls LaunchPrefab
and then calls LaunchPrefab
and then calls LaunchPrefab
Did you check the linked docs for StartCoroutine?
There's literally a code example of almost exactly what you want to do, with an explanation
and so on
Check the docs and think for a bit
Do you want to start a timer every frame
That isn't how you would Start a Coroutine. That would be an infinite loop.
im thinking for 6 hours straight i just wanna finish this and go to sleep
no i dont think so
Then the docs will show you exactly what to do
How to start it and loop it correctly
Check the documents, it shows how to run a looping coroutine
https://docs.unity3d.com/Manual/Coroutines.html
i dont think i get it but do i have to put my yield on the end of the coroutine?
It's pretty straight forwardcs void Update() { if (Input.GetKeyDown("f")) { StartCoroutine(Fade()); } } IEnumerator Fade() { Color c = renderer.material.color; for (float alpha = 1f; alpha >= 0; alpha -= 0.1f) { c.a = alpha; renderer.material.color = c; yield return null; } }
Let me explain to you how code flow works with coroutines.
Code runs one line at a time. An object gets created, then the Awake on it runs.
Whenever you hit StartCoroutine, the instruction pointer will jump into that coroutine function, and continue to run one line at a time until it hits a yield return, at which point it goes back to where the StartCoroutine was called and continues as normal. When the time is up, the instruction pointer jumps back in to the coroutine, the line right after the yield, and continues from there.
Whenever the code hits a while loop, it checks if the condition is true. If it is, then it enters the body of the loop (inside the {}) and runs it one line at a time. When it hits the end of it, it goes back to the loop condition and checks it again. If the condition is still true, it repeats. Whenever it checks the condition, and it is false, it will skip to the line after the loop body.
public void Main() {
StartCoroutine(LoopCoroutine());
}
IEnumerator LoopCoroutine() {
while (...)
// Code here
yield return new WaitForSeconds(1f);
}
}
copying the example i stared at for 3 mins doesnt help sry
So look at it for longer until you figure out what it's doing
instead of copying, learn what it's doing
What do you not understand (other than just making what you had work)?
Ah Digi's given a pretty thorough and lengthy explanation of the procedural process - how things are processed, line by line.
oh wait. i have to put the loop in the coroutine?
Yes, as all the examples in the docs showcase
im like drunk but without alcohol rn i dont understand what i see untill someone tells me. then i see it.
Then come back when you're in the proper headspace to learn
yo im developing a building system for my 2D top down game that uses SetTile where you place down Wall tiles with a Tilemap collider, and each tile needs to have their indivisual currenhealth variable. How can I make it so that each Wall placed down has their own indivisual health using Tilemaps
possibly some sort of Wrapper for each tile
(is this even possible)
but i think im getting it now
{
LaunchPrefab();
}
IEnumerator LaunchPrefab()
{
while (projectile.GameOver == false)
{
Instantiate(projectilePrefab, transform.position, Quaternion.Euler(0, 0, 0));
spawnRate /= IncreaseMultiplier;
yield return new WaitForSeconds(Random.Range(spawnRate - 4, spawnRate + 4));
}
}
sth like that?
You're not acquiring certain info from the docs. You need to Start the Coroutine.
{
StartCoroutine(LaunchPrefab());
}
?
no
2 brackets to much (idk if thats how its called)
The basic get up is (without randomly guessing - pseudocode):cs Start/Update if(...) StartCoroutine(...) Coroutine while/for/loop stuff yield
learning by doing๐
Where the docs would discuss the specific details and illustrate proper syntax.
ok ill go to sleep ill try again tomorrow
hey guys. Im working on a 2d platformer and want the sound effect for running to unpause when the player is on the ground & moving, and pause when the player is not moving, not on the ground, or both. This functionality is called in Update(). I know it needs if statements, else if, and else, but I can't get it right. This is my code so far. https://gdl.space/jowexetina.cs & the Audio Manager script: https://gdl.space/fucikedifa.cs
but I can't get it right
Can you explain whats wrong right now?
As you can see the audio plays for a short bit but sounds very wierd, and then it stops completely
please convert the video to something we can watch in discord ๐
tbh it sounds like its toggling between playing and pausing pretty quick, you should add some logging to see how often it switches and then to figure out why the planned if statements fail
so im trying to make a text appear on the screen when the enemies start spawning but im not sure how can i deactivate it after activating it https://pastecode.io/s/3hqbsu2j (heres the enemyspawner script)
you would be hiding the text here and instantly showing it again but you just have to return the wait again and then disable the text
I'd also enable the stats window and see if there are fps/CPU time jumps.
Nvm. Didn't read the context.
inbetween while (canSpawn) ?
okay it works and it disappears but i only want it to appear once and not repeat everytime it spawns an enemy
Then I would start a second coroutine that just does that and contains no loop
Unless you are working with DoTween or any other library that brings a delay functionality
i just stupidly followed a tutorial and i think i writed somewhere sth which was just an example name but idk what
uhh what is your question?
why isnt the isDefend bool triggering
yes it is toggling between paused and unpaused every frame it seems.
you need to set the "isDefend" on your animator, not just the variable in the script
Yes, you are never setting that bool to true in your script
the internal property isDefend is not triggering the animator, do m_Animator.SetBool("isDefend", true/false);
@silk night apparently AudioSource.isPlaying doesnt differentiate btween paused and unpaused.
Well that would explain it ๐ I was a bit confused why you would have pauseOrUnpause as a function, toggling without knowledge of current state may have some uses but it mostly leads to bugs like this, rather have one pause and one unpause function and only call them when you are sure of the state
tried doing that and it doesnt work so ripperino
How does your second coroutine look like?
still not working :(
tried my best
Put Debug.Log at the positions where it should trigger, if it does not trigger at all find out why, my wild guess is the shuriken has no Shuriken tag
Enable before the yield return, disable after and remove the enable from the loop function
then lets go Logging, find out what is triggering and whats not
so basically this right?
yes
Also you should make your function names more descriptive, like "ShowEnemiesIncomingText", might be a bit tedious to have longer names but imagine yourself in 3 months coming back and not knowing wtf EnemiesIncoming is ๐
btw this too if it helps
Oh, you have a smallercase i, animator has capital I
yee i always do that , this time it was to test things n stuff
i found it myself btw
so i added this
and this
and this happend
Looks like you accidentially reset your reference to the animator in your script, just drag it into the field again
uhhh... what's the deal here
GetComponent in Update?
Trying to use it in Start before it's assigned?
to be honest it looks like you mixed up your Start and Update to me
oh wow, didnt even see that its switched ๐
well you are still trying to use m_Animator before you assign it
i mean you're clearly still trying to use it before assigning it...
do you understand how references work and how = works?
just like 10%
= is the assignment operator. It assigns a value into the variable on the left side.
x = 5; < this assigns 5 to x
now if we do Debug.Log(x) we see 5
references work the same way
m_Animator = GetComponent<Animator>(); this fetches the animator from our object and assigns it into the m_Animator variable
now we can use the animator
but... we can't use it before we do that, unless the variable was otherwise assigned.
and it also won't work if GetComponent<Animator> returns null for some reason, for example there not actually being an Animator there
is there an error in the console?
https://pastecode.io/s/rebjcyj8 (WaveStartAndStop)
okay so im trying to make a button that starts a wave and stops it and i have multiple spawners in the scene in different locations and with different spawnrates but the problem is on how im referencing the enemySpawner script , is trying to gind a gameobject with the tag Spawner but since i have multiple , its just gonna get one of them , so i got 3 spawners and the WaveStartAndStop script will get the spawner 2 enemySpawner component , so how i can reference one script that is the same from all the spawners
Trying to do everything with tags is a bad idea
Are the spawners in the scene from the start or are they themselves spawned by some kind of script?
If they are, make the Property on the script a List<EnemySpawner> and then find the WaveStartAndStop in the inspector and fill the list with all EnemySpawners by dragging the gameobjects they are on onto the list
afterwards you can access the list with loops instead of a single spawner
they are in the scene from the start
Yeah then just do what i wrote ๐
i did but i cant use the variables from the script no more now
it's a list.... you would call those things on individual elements of the list, not the list itself
so im kinda frustrated rn because i my characters animation is teleporting me to another Position but i cant find anything to undo it
The keyframes of the animation will control it.
Usually it's not a good idea to animate the root object with an animator though
it ends up doing this - overriding your controls
you generally want to only animate child objects
how do i do that
Simple - instead of animating the root object in your scrubsheet, animate child objects instead
just make sure the bits that need animating are not on the root object
move any renderers etc to child objects
so i have it like that: Enemy GameObject has with all Scripts and Animations
and i should put Enemy in an Empty GameObject and split animations and rules?
- Root: Scripts, Animator, Rigidbody
- Child: Character images <-------- Animate the position of this one
- Child of child: Stuff like weapons or equipment that is visible
but isnt the animator the thing which changes the gameobject which is connected to it :(
it can change any object in its hierarchy
Animator is just the control center of animations
it all depends what you set up in the scrubsheet
yeah what praetor said ๐
with the keyframes
too many words i dont understand ngl
FOr example this animation clip is animating many child objects
you can see the paths to the objects on the left side
and the keyframes on the right
Your animator is like a control center
It can contain many animations and control when to play which one
Any animation can change the root object (where your animator is on) or any object below it
so the Animator is like Photshop Animator and i add components like pictures to it (childs)
Not familiar with photoshop animator >_>
https://img.sidia.net/ZEyI5/ZusAFAPu81.mp4/raw as you can see, the root never leaves the position, only the image part moves
so your player would technically still be on the original position, just some image gets moved around
yeah thats why you should animate a child object of the player, not the root
didnt change a thing on my main character and now he just disappers
i have many scripts which delete him but none of them are instant on the field
by removing the box collider i stopped it
Any idea why this always return's the same value?
{
float x = Random.Range(MapManager.Instance.MapX, MapManager.Instance.MapXMax);
float y = Random.Range(MapManager.Instance.MapY, MapManager.Instance.MapYMax);
Debug.Log($"Generated Random Position: x={x}, y={y}");
return new Vector3(x, y, 0);
}```
void Start()
{
MapXMax = GameMap.cellBounds.xMax;
MapYMax = GameMap.cellBounds.yMax;
MapX = GameMap.cellBounds.x;
MapY = GameMap.cellBounds.y;
Debug.Log($"MapManager Started, MapXMax: {MapXMax}, MapYMax: {MapYMax}, MapX: {MapX}, MapY: {MapY}");
}
MapManager Started, MapXMax: 32, MapYMax: 18, MapX: -38, MapY: -36
this is constant valve that is always returned
Generated Random Position: x=-16, y=-36
log the instance's value of map x and map x max before using it with random range
How come on a MonoBehaviour, i can reference a prefab with a ComponentType
[SerializeField] private MyPlayer PlayerPrefab; and i can use the inspector to search prefabs that have the component, but i can't do the same thing from a scriptable object, the same kind of SerializeField just doesn't come up with anything.
SOs cant find scene objects
Can you show some illustrations of the component type you're wanting to reference, the field and inspectors?
I'm not looking for scene objects, i'm loooking for prefabs at the asset/project level
I make an empty game object, add any monobehaviour to it let's say "MyPlayer"
Then i can make it into a prefab into my assets folder.
I'm able to find it from the inspector on game objects or drag it into MyPlayer typed properties on Monobehaviours, but not ScriptableObjects
You tried directly dragging the prefab/asset inside it
yes
Generated Random Position: x=-16, y=-36
Spawning LightningStrike at (-16.00, -36.00, 0.00)
Instantiated LightningStrike(Clone) at (-16.00, -36.00, 0.00)
Distance to player: 42.70246
private IEnumerator SpawnWeatherEffect(GameObject prefab, int count, float effectDuration)
{
for (int i = 0; i < count; i++)
{
Vector3 position = GetRandomPosition();
Debug.Log($"Generated Random Position: x={position.x}, y={position.y}");
Debug.Log($"Spawning {prefab.name} at {position}");
GameObject effect = Instantiate(prefab, position, Quaternion.identity);
Debug.Log($"Instantiated {effect.name} at {effect.transform.position}");
activeWeatherEffects.Add(effect);
if (currentWeather == WeatherState.Thunderstorm)
{
float distance = pathFinder.GetDistanceBetweenGameObjects(Game_Manager.instance.player.gameObject, effect);
Debug.Log($"Distance to player: {distance}");
AdjustWeatherEffectBasedOnDistance(effect, distance);
AssignThunderAudio(effect);
AdjustThunderAudioBasedOnDistance(effect, distance);
StartCoroutine(DisableSpriteAfterTime(effect, effectDuration));
}
else
{
StartCoroutine(DestroyAfterTime(effect, effectDuration));
}
yield return new WaitForSeconds(0.1f);
}
}
I do not see the log information for the values being used with Unity Random.
Log the arguments that you're using with Unity Random
If it's (-16,-15), you'll only get -16
Random.Range with mapX: -38, mapXMax: 32, mapY: -36, mapYMax: 18
Generated Random Position: x=-30.97226, y=-13.01677
every time i play the scene and hit my hotkey to run the script it changes the position, It has to be something with my Coroutine?
Maybe consider showing us the Get Position function
private Vector3 GetRandomPosition()
{
float mapX = MapManager.Instance.MapX;
float mapXMax = MapManager.Instance.MapXMax;
float mapY = MapManager.Instance.MapY;
float mapYMax = MapManager.Instance.MapYMax;
Debug.Log($"Random.Range with mapX: {mapX}, mapXMax: {mapXMax}, mapY: {mapY}, mapYMax: {mapYMax}");
float x = Random.Range(mapX, mapXMax);
float y = Random.Range(mapY, mapYMax);
Debug.Log($"Generated Random Position: x={x}, y={y}");
return new Vector3(x, y, 0);
}```
That would be where you're getting the (-16, -36) from
What did the log print
Random.Range with mapX: -38, mapXMax: 32, mapY: -36, mapYMax: 18
Generated Random Position: x=-20.58329, y=-30.5786
Spawning LightningStrike at (-20.58, -30.58, 0.00)
Instantiated LightningStrike(Clone) at (-20.58, -30.58, 0.00)
Distance to player: 39.93124
Assigned Thunder Audio to LightningStrike(Clone) at position (-20.58, -30.58, 0.00)
Random.Range with mapX: -38, mapXMax: 32, mapY: -36, mapYMax: 18
Generated Random Position: x=-20.58329, y=-30.5786
Generated Random Position: x=-20.58329, y=-30.5786
Spawning LightningStrike at (-20.58, -30.58, 0.00)
Instantiated LightningStrike(Clone) at (-20.58, -30.58, 0.00)
Distance to player: 39.93124
this is two Instances of the instanitation
So the positions are fine and everything works as expected
but wouldnt this from the coroutine
for (int i = 0; i < count; i++)
{
Vector3 position = GetRandomPosition();
call a different postion for each iteration through the loop?
What's the issue here?
I'm pretty sure it is
Chances are, all of your objects are the same object if they all share the same values
You'll need to provide more information if you aren't wanting us to guess
They are the same object, But wouldn't this
GameObject effect = Instantiate(prefab, position, Quaternion.identity);
update the positon of the object? they are all currently spawning in the same location.
How are you determining that the positions are all the same?
Show logs for each object being instantiated and the position they're given
Random.Range with mapX: -38, mapXMax: 32, mapY: -36, mapYMax: 18
Generated Random Position: x=-20.58329, y=-30.5786
Generated Random Position: x=-20.58329, y=-30.5786
Spawning LightningStrike at (-20.58, -30.58, 0.00)
Instantiated LightningStrike(Clone) at (-20.58, -30.58, 0.00)
Distance to player: 41.34794
Assigned Thunder Audio to LightningStrike(Clone) at position (-20.58, -30.58, 0.00)
Random.Range with mapX: -38, mapXMax: 32, mapY: -36, mapYMax: 18
Generated Random Position: x=-20.58329, y=-30.5786
Generated Random Position: x=-20.58329, y=-30.5786
Spawning LightningStrike at (-20.58, -30.58, 0.00)
Instantiated LightningStrike(Clone) at (-20.58, -30.58, 0.00)
Distance to player: 41.34794
Assigned Thunder Audio to LightningStrike(Clone) at position (-20.58, -30.58, 0.00)
Random.Range with mapX: -38, mapXMax: 32, mapY: -36, mapYMax: 18
Generated Random Position: x=-20.58329, y=-30.5786
Generated Random Position: x=-20.58329, y=-30.5786
Spawning LightningStrike at (-20.58, -30.58, 0.00)
Instantiated LightningStrike(Clone) at (-20.58, -30.58, 0.00)
Distance to player: 41.34794
Assigned Thunder Audio to LightningStrike(Clone) at position (-20.58, -30.58, 0.00)
Random.Range with mapX: -38, mapXMax: 32, mapY: -36, mapYMax: 18
Generated Random Position: x=-20.58329, y=-30.5786
Generated Random Position: x=-20.58329, y=-30.5786
Spawning LightningStrike at (-20.58, -30.58, 0.00)
Instantiated LightningStrike(Clone) at (-20.58, -30.58, 0.00)
Distance to player: 41.34794```
Well, during this function all of your calls to Get Position are returning the same values
hello anyone can help me with respawning?
Show us what you have so far
I have python programming background and im new to unity and C#. I am following youtube tutorials on making a 3D fps game. I am trying to figure out the falling/dying + respawning part right now.
Make sure you aren't touching the init state prior to the next iteration of the function call - you're likely resetting the seed between each call somewhere. Try commenting out stuff or the entire body of this coroutine and simply call and log Get Position a few times.
Do any of those logs get called?
Yes, the logs are called, and the position of the camera and player seem to be updated. but in the render I just fall through the trigger
The respawn trigger has a rigidbody? Odd.
What does the player have
player have rigidbody
trigger has rigidbody and box collider and I checked the box IsTrigger
im not sure what I did wrong, but from what I understand, player.transform.position is the variable that holds the player position, transform is the category and position is under the transform category. By setting it to equal the respawn point I can teleport to the respawn point. I also tried setting it to a vector3 and it also didnt work
The camera should follow the player right? would it be that im just setting the gameobject player to respawn but the camera falls through?
what is odd about the respawn trigger having a rigidbody?
What do you think is the problem here
Commenting out the GameObject effect = Instantiate(prefab, position, Quaternion.identity);
gives the variable the different randon positions, the second I uncomment it again it goes back to spawning it in the same place. I got closer thanks!
Check out the prefab and make sure it isn't resetting the random seed in awake/start/onenable etc
i keep gettig an error idk where the problem is
my ide is configured it should underline the error
it only comes up when i run the game
That is a runtime error. Your ide will not underline it
Controller is null when you try to access it
Is the script you've shared Assets/Character.cs?
yea
The class name should be Character rather than Example - the name of your MonoBehaviour should match the name of the file
Unless it is editor version 2022.2+
Still good practice though
ohhhhh
Oh I totally had no idea that that became a thing. I'll have to look into that ๐
That is not related to your error though
so how do i fix
Make sure controller is not null at that time, use a debug.log
man i started literally last night idk any of these words
The rigidbody component tells the physics system that it is using physics. Usually a trigger area like yours is not a physics object (it does not move or fall or get pushed)
Have you been going through !learn ?
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
Debug.Log specifically should be something you know already. Often it is taught VERY early in a course
ill go rn i didnt know its a thing
Your player IS moving it looks like. So perhaps something else is setting the position back
Is there a CharacterController on the player along with the rigidbody?
I removed it and it still doesnt work.
I tried adding a script in the players movement code, just to test the set location.
I added transform.position = respoint.transform.position; with Serialize field respawn point and it works when the code is in the player
my player has character controller
does it matter what type of object (gameobject / capsule / etc) my player is?
Removed the rigidbody? That would not fix it, nor is it related to your issue. It was just something I was noting
Yes, the CC is the entire problem
You have to disable it, teleport, then re-enable it
Otherwise it IMMEDIATELY resets the player position to where it was last
wait I dont get it can you explain why
Btw, a rigidbody and CharacterController should never be on the same object.
There are some times where a KINEMATIC rigidbody is ok, but that is kinda niche.
You could actually justify the trigger area having the rigidbody to get around this issue forgot that OnTriggerEnter does work with CharacterController
Only OnCollisionEnter does not
Because the CC tracks where it is, and uses that for where it moves next. If you disable it, you break that tracking and "reset" it
Just disable the CC, move it, then re-enable it
cuz im still relatively new, and I just followed some youtube guy and did CC
can you show me the code to disable the CC?
MyCCReference.enabled = false
transform.position = whatever
MyCCReference.enabled = true
sorry i dont understand ...
do I have to reference the CC as a serialize field?
or do I just do use the player in the serialize field and use
player.CharacterController.enabled = false;
just do GetComponent in OnTriggerEnter
TryGetComponent is better, so I'm gonna show that. It will likely introduce something you don't know, which is the out keyword. That is basically just a second return. TryGet returns a bool telling you if you actually found the component, but you also get the reference "out"
if (other.TryGetComponent(out CharacterController cc)
{
cc.enabled = false;
cc.transform.position = respoint.transform.position;
cc.enabled = true;
}
does this work
Yes, I would validate the collision though. Either check if cc is null before using it, or check the tag or something (or both)
Because right now this will run that code on ANY collider that enters the trigger area
but when i run this it doesnt rly work
Do you still have a dynamic rigidbody on one of the objects?
OnTriggerEnter requires one of the two to have one
yes
Ok and what is not working?
Do you get any errors?
the name cc does not exist in the current context
do I have to use a type like int / float ? what type is cc
Oh of course. That is simply not how you declare a variable.
You need to include the type on line 19
CharacterController cc =
By the way, your ide is not configured.
!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
Third link โ๏ธ
whats the use to config the ide
thanks!
It will underline errors, and suggest fixes for them. It also enables fuller code completion (for unity specific properties/methods)
ok thank you
Trying to make it so players cannot sprint while crouched, instead of doing this:
if (isRunning)//If player IS holding LShift
{
if (!isCrouching)
{
playerSpeed = runSpeed;
}
}
else//If player is NOT holding LShift
{
playerSpeed = walkSpeed;
}
Can I just do:
if (isRunning)//If player IS holding LShift
{
(!isCrouching)
playerSpeed = runSpeed;
}
else//If player is NOT holding LShift
{
playerSpeed = walkSpeed;
}
The only difference is removing the braces from the second if statement? Or am I missing something?
yes, removing the if statement to check if a player is crouching
i know i can do stuff like that in javascript, but idk if c# works the same
Ah, it is not fully removed so I was confused haha
sorry yeah, kinda just threw that together
It will set playerSpeed to runSpeed whenever you hold left shift. Whether crouching or not..
how would i go about making it not set to run speed when holding crouch?
You can make the first if statement into if (is Running && !isCrouching)
Just combine them
๐ 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.
Player cannot move at all and am getting the following error:
https://hastebin.com/share/avoderaroj.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
yes what is Horizonal ?
yeah that would be Horizontal
wish vscode would underline that LOL
impossible
the compiler has no idea if the string is valid for it or not
it just knows Oh its a string, good to go
well i did that any my player is just flying straight into the air LOL
btw you should not move transform.positions with any physics objects
including character controller
so instead of transform.position i should be using characterController.Move?
yea
not saying thats fixing whatever you said was broken, but if you want collisions to actually work properly then absolutely
so something like this?
characterController.Move(transform.position + playerMovement.normalized * playerSpeed * Time.deltaTime);
you can remove transform.position
do i not need to grab the current position?
when?
as soon as the game starts
can you show the player inspector + showing all the gizmos
yeah, i want to be able to set how high the player can jump, so i can tweak it if needed
yeah but right now you're telling to Keep flying up 7 units at time every frame
thats not setting your jump height
oh
look at the example i sent for CC.Move it shows how you have to make gravity(create/track vertical velocity) if you want jump to work
not really understanding what this means, and I don't jsut want to "write what it says and move on". can you explain?
if (move != Vector3.zero)
Is it true that programming your animations for UI is better than using Unity animations. I heard that animation updates every frame even when finished or something similar which makes it bad for performance
Looks like an if statement that checks if the input vector named move is not equal to zero; basically saying if there is any input at all, do X
Though that's my uneducated guess.
it checks if there is any movement
yeah, i did basically exactly what that says (adding my own variables in some places) and it's still sending me flying
void Update()
{
if (!PauseMenu.GameIsPaused)//Checks if the game is NOT paused
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
playerIsGrounded = characterController.isGrounded;
if (playerIsGrounded && playerVelocity.y < 0)
{
playerVelocity.y = 0;
}
float x = Input.GetAxis("Horizontal");//Left->Right
float z = Input.GetAxis("Vertical"); //Forwards->Backwards
Vector3 move = new Vector3(x, 0, z);
characterController.Move(move * Time.deltaTime * playerSpeed);
if (move != Vector3.zero)
{
gameObject.transform.forward = move;
}
if (Input.GetKey(KeyCode.Space) && playerIsGrounded)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravity);
}
playerVelocity.y += gravity * Time.deltaTime;
characterController.Move(playerVelocity * Time.deltaTime);
}
}
}
can you record a short video
sure thing!
gravity should be negative no?
welp
put -17 instead of 17
no longer flying
but im not moving
im rotating on the axis
just looking left/right
remove the transform.forward = move
if this is fps
a lot of this needs to be changed
can't do anything now
wait, i might know why
yup
i was using player speed (set to 0 by default)
i swapped to walkSpeed and it works
I need some help:
While using 2022.3.ff1, I typed the following in an if statement:
Keyboard.current.leftArrowKey.isPressed
Originally, people needed to include
using UnityEngine.InputSystem;
to get it to work but it looks like that namespace is no longer necessary.
With or without that namespace, I get the following error whether or not I have the Input System package installed:
Error (active) CS0103 The name 'Keyboard' does not exist in the current context Assembly-CSharp
I looked online but am having trouble finding a correct solution. So far the solutions have been to add the namespace but those are outdated or to add the Input System package but that didn't work either
this error looks like its from VS, did you check the references for all valid assemblies?
Yes, it's from VS.
did you check the references for all valid assemblies?
^ This is new language to me. What do you mean by this?
in the solution panel you will find all hte assemblies, see if any show a warning icon first
says who ?
" looks like that namespace is no longer necessary. "
There's no warnings if I've understood you correctly.
no, over in the solution panel
can you screenshot the whole ide
why are you still on vs2019
why do you care?
because its important to see the complete ide
I'm redoing a basic basic intro to 2D Unity tutorial and it was commented here. At first I thought the commenter was an official but may have been mistaken. (the bottom comment)
i was gonna say, do you have the input system installed in unity?
I do
another question is does the error actually show up in unity as it tries to compile it
It does
however:
these assemblies don't look right nvm thought OP sent this
After re-adding the "using UnityEngine.InputSystem;" code back in after adding the Input systemit seems to be working now....? I'm not sure if it just needed time or what. I had turned VS off and on again and it didn't solve it earlier so I'm not sure why it's working now
keep in mind Unity and VS are seperate, it could fail to compile in VS and yet work in Unity if for soem reason your assemblies aree't the same
Maybe I hadn't tried all 4 combinations of having the Input package, not having it, having the namespace, not having the namespace until now?
couldve just been a small bug, but most likely user error. The comments you read on that tutorial arent true though because Keyboard is under UnityEngine.InputSystem
yes that dude is talking nonsense
thank you.
putting new input system inside UnityEngine would defeat the whole point of using packages
they're made so they dont have to update/release the whole app to fix 1 thing related to inputs
It must have just needed time to fully integrate the Input package because only a moment ago did Unity have the popup saying to Enable backends or something for keybaord input
regen project files sometimes can help
uh oh, after restarting after enabling backends it's making me enter w/safemode.
....wait, nvm. It's just bc I re-commented out the namespace to test something ๐
did you save with compile errors?
surprised the unity learn site is even using Keyboard.current
I had done this tutorial a few years ago and it used something like that back then too. Can't rmember if it was exactly the same. They've changed it.
Thanks for the help you guys
Mainly am doing this tutorial to remind myself how to make a 2D Player Controller and have it interact with colliders.
I'm guessing there's already some player controllers like this in the Asset Store but was only seeing ones for platformers.
It's good for me to redo this though. I'm super green again despite programming all through college haha
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);```
anyone know why this code makes it so the 'looking of the mouse' is like... wrong?
it's turning based on the mouse
but my mouse is to the right and it's looking up
if my explanation is off I can record a video of it rq
I tried to find a video to explain how to make it but each video has a similar issue of the character not looking at the mouse
i dont see an error exactly with this. Can you show a video of it, or what arrow of the object (green, red, blue) do you expect to be pointing towards the mouse?
sure give me a minute or honestly three
I realized the camera was on the player which could of caused the issue but it still wasn't
It's like 90 degrees off
I fixed it by removing 90 from the angle
idk how it works but it does
mb
click on the object you have, its red arrow is likely pointing towards the mouse, which is the "right"
You could also just change the object so its facing right to begin with, rather than up
I mean, I fixed it by just minusing 90 degrees from the angle
I guess it's kinda the same deal as making it start as right instead of up
4k120 screen XD
what
that works, but im not a major fan of code fixes when its an issue with the object itself. Though i dont do 2D so i dont know how objects are expected to be oriented.
If you use this on another object which is positioned "correctly", suddenly this script is now 90 degrees too far
It's not that the screen looks very big
ah
I have a big monitor ๐
only one though which sucks
worst part is I'm going to college soon so getting a second monitor would be worthless in two months
And I have a laptop that is sh*t sorry for the bad word but yes
We should merge our devices to make an average one
My laptop has 4 ram with a 2.30ghz Pentium inside t4500 processor but it is WELL MADE GARBAGE
I have a computer and I don't remember the stuff inside it
That's why I had to change to the "old" laptop so to speak, it's been with me for 1 year, well 1 and a half of this year.
I forgot to clean it for 3 years which almost caused it to get set on fire
smelt like smoke
just saying, off topic isnt really allowed in this server
If true...
on topic, for an attack delay, lets hypothetically say a punch, would using a coroutine be good for the punch animation of the punch or is there a better way?
As you say
๐
depends what you mean "coroutine be good for the punch animation". Are you still making an animation itself, or planned to define the animation in code?
Id prefer to do things in update since you'll likely be punching often and I find a lot of logic is easier if you need exact control of when things start/end
I'm making an animation for the punch using the animator
well I just made it
so tried for a good amount of time and im afraid of infinite loops so does this work properly or am i stupid? ```using System.Collections;
using UnityEngine;
public class CanonMain : MonoBehaviour
{
public GameObject projectilePrefab;
public float spawnRate;
public Projectile projectile;
private float increaseMultiplier = 1.05f;
void Awake()
{
StartCoroutine(LaunchPrefab());
}
IEnumerator LaunchPrefab()
{
while (projectile.GameOver == false)
{
Instantiate(projectilePrefab, transform.position, Quaternion.Euler(0, 0, 0));
spawnRate /= increaseMultiplier;
yield return new WaitForSeconds(Random.Range(spawnRate - 4, spawnRate + 4));
}
}
}```
dont see anything wrong ๐คทโโ๏ธ
you could use a coroutine or update, the same could be done in either. But just know coroutines run after update, according to the execution order https://docs.unity3d.com/Manual/ExecutionOrder.html. So if some of your punching logic is in update, and the "punch ending" logic is in the coroutine, you might not have a properly accurate start and end.
thank you tried until 0:30 yesterday but i think i was just way too tired
I'll give it a try
but also
spawnRate /= increaseMultiplier; seems weird. "Multiplier" yet its being divided
the only sus thing I would see is spawnRate , idk how WaitForSeconds would act with negative numbers
how can you get a negative number by dividing 2 positives?
ok i rename it
its long to explain my problem in words so i illustrated it.
my enemy script has logic for seeing the player (the enemy can only fire if the player is in line of sight).
i do this using a raycast
Physics.Raycast(eyes.position, transform.forward, out hit, distanceToAttack + playerSightRange, playerAndBlockLayers);
eyes is a transform where the "face" of the enemy should be, playerAndBlockLayers is a layermask that includes the enemy layers, the player layer and the ground / obstacles layer
the system works fine when the player is standing but the moment the player crouches suddenly the raycast goes through walls and the enemy cannot have line of sight with the player
why
well what is spawnRate?
13 i think
look at the logic youre doing. spawnRate = spawnRate / some number. This i assume relatively often.
Random.Range(spawnRate - 4, spawnRate + 4)) you can surely see why a positive number subtracted by something may be negative
oh yeah thats right
i stg im fucking stupid i changed "transform.forward" to "eyes.forward" and it instantly got fixed bruh
this drawing looks like your assumption of whats happening, rather than whats actually happening. Are you using debug.DrawRay to visualize your raycasts? Nothing in the code you've shown cares about where the player is
dw i fixed it lol
fun fact: new physics debugger tab has now "Casts" you can see all types of casts
still, read my advice. Use debug.DrawRay to visualize your raycasts. your problem came because you assumed whats happening rather than knowing for real. And the assumption was wrong
would it help to set the -/+4 to a percentage of spawnrate?
problem is the enemy object is locked on Y rotation so it couldnt rotate the transform.forward whent he player was crouching, so i just changed to the eyes which can rotate as they please
i was already using gizmos to visualize the raycast thats how i knew that was the problem
oh right wait i didnt use drawray
bruh im stupid lol
gizmos? and if you saw the raycast then you would see it wasnt pointing downwards and going through the player
which is what your drawing had
yeah im stupid lmfao
๐คทโโ๏ธ idk what behaviour you want, this logic is flawed from the beginning. I suggest you do this mathematically first to understand why this will always start to break after a few minute
step away from the code because its likely just confusing you more. Do it with real numbers and see what these values lead to. Maybe plot it on desmos if you know how
but if my spawnrate is 13 and it keeps getting divided by 1.05, it should work if i set the 4 to half of the spawnrate for example
just do the math on it, or
with proper debugs so you can see the math yourself. Leave it running for a few minutes and itll become clear
also why doesnt it stop when GameOver = true;? i tested it and gameOver is actually true so why doesnt my while loop stop?
did you debug.log projectile.GameOver
yes
the one on the instance
it says true
in the inspector?
if (explodingTime <= 0)
{
GameOver = true;
particle.Play();
StartCoroutine(Wait());
Debug.Log(GameOver);
aud.Play();
}
and if you click Projectile it takes you to the one that says true?
wdym?
i click on the clone which is exploding and it says true for 0.6 seconds untill it gets deleted
this doesn't make sense to me, you're looking at the projectile instance but you linked it in the inspector ?
Some simple debugging really is gonna show you why all this is happening
what did you link in the inspector in public Projectile projectile; this isn't what ur spawning btw
I would rewrite this whole thing
wait i linked the prefab but the prefab doesnt change does it?
you need the gameover from the instance
but in the while loop it wont make sense
since you have to create it first
i have 2 days until deadline for the gamejam im taking part
Just wait until it runs for a few minutes and they realize the issue of the math and itll have to be rewritten
that too
usually rewriting is faster and most likely something better
i have no idea how i should rewrite it
first use a Global gameover bool
not the one on bullet
have bullet only affect whichever script has that public bool gameover (ideally you wuld use method instead of directly touching a public var)
how
like a singleton or something
Imma be honest, if your goal is just to publish the bare minimum that runs, you shouldnt be using game jams to learn. You clearly are ignoring basic debugging steps as well, something I know that you've done for the spawn rate before in a past convo.
This isnt the way to learn, this is just struggling but on a deadline
gamejam is good practice, not so much learning if you're pressed on time
what is a singleton?
Goodluck with this one 
but I would follow bawsi's advice here
debugging should be your #1 priority
plan out your loigc a bit more before putting any code
for some reason my player flys whenever i press space and never goes back down https://paste.ofcode.org/nGZr3WQC6yCzLLfBFcQPRM
im not sure if this is the right channel soryr
large code should be sent as links
โฌ
๐ 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.
thank you
is this a rigidbody controller?
btw for future no need to put multiple classes in 1 link that can get confusing if we're looking for speicifc lines
oh alright sorry
btw https://screenshot.help :p
oh yea Kinematic wont go anywhere unless specifically told to
also should not use Translate to move rigidbodies
my computer is slow ๐
oh okay
what should I use?
not sure how taking a screenshot would affect pc speed lol
I mean you're running unity on the pc, it can handle a screenshot
i tried opening snipping tool and it was super slow Iโm using Boot Camp so Iโm not sure if the controls are the same but Iโll give it a try
itโs a super old mac
alright I turnt off kinematic and and my body Is shaking a bunch and stuff
i wanted to install window games
I didnโt think Iโd ever use unity
wdym
omg it worked it worked it worked i used an singleton and now all movement stopped, aswell as spawning!!!
I might redo the code for player movement
thats good, the advice is still valid. Also just careful over-relying on singletons
yeah i read that you should use them with care
yeah they can be overused because they are so easy to use
but then it just becomes a mess of singletones instead of properly injecting components
having this glitch dk why can anyone help
this isn't a "glitch"
it tells you exactly whats wrong
using Camera.main without camera tagged in scene wont work
why doesnt it recognise setActive?
what is GameOverCanvas
typo
it should be capital S
wonder why VS not correcting you on that
my keyboard is shitting bricks 
this is not the first one
but even if i type just "se" it doesnt show setActive
what is GameOverCanvas
it wont do setActive does not exist
my canvas which should just get enabled when gameOver is true
what type
is it
Im so happy I found the tags
Components are better ๐
if its Canvas does not have SetActive
only gameobjects do
canvas.gameObject.SetActive
if it wasn't showing up, it didnt exit ๐
that worked ty
not really a code question
how am I to know
because you didn't write code to do it 
anyway post in #๐ปโunity-talk and show actual details of the setup including camera culling layers etc
i have a function that takes a range/int and uses that to find all the tiles/vector2s around a position that are in range, it then puts that into a list called inrange2 then it sends that list to another function. the issue is im using 2 for loops one inside another to find where all these positions are and it seems to be crashing my game. the range given is always 2
The second loop is missing the i++ part
I dont see why you need the second loop or the inrange2 List. Just call inrange with the new Vector2
oh ya true
can you use navmesh to make agents find new paths if the current one is blocked by another navmesh agent?
or would I have to code that feature myself?
anyone got any idea why the Character Controller Component likes to flicker isGrounded? really awesome
is there any short cut or plugin to implement wait for seconds
like the whole i enumerator thing
just for adding wait for seconds
i love unity
why would you need that? you can just use the IEnumerator
ok
also keep in mind, if you are planning on changing the game speed at any point with a speed up button etc but you want the wait for seconds to remain the same, use WaitForSecondsRealtime
oh ok thanks
if(!revived){
deathScreen.SetActive(true);
lastChance.SetActive(true);
}
else{
deathScreen.SetActive(true);
}
finalScore.GetComponent<TextMeshPro>().text = Score.ToString();
finalScore is a child of deathScreen, why does it say me object reference = null?
Maybe I can't change components of a gameobject I just activated in the same frame?
I need help please
And when I do Debug.Log(finalScore) it write "FinalScore (UnityEngine.GameObject)"
Try replacing TextMeshPro with TMP_Text
Hello ๐
FYI, TextMeshPro is not the component that you are using here. That's why you got a null ref. TMP_Text is an abstract class for all Text components in TMP
is there a way to check which navmesh surface a navmeshagent is on currently?
there is a crude way
NavMeshSurface.activeSurfaces->NavMeshData.sourceBounds->bounds.Contains(agent.transform.position)
i ended up using a very amateurish method where i just check if their x position is higher or lower than a wall
and that did the trick lol but i hate using workarounds like that
@slender nymph
#๐ปโunity-talk message
- I have
UnityEvent(s) in my Singleton. This is due to Project needs, i wont change it to static or anything else. It must be serializable, in scene without any references to other scene object. I need to unregister events. - You are right but not works as i mentoined.
if the intention is just to unsubscribe from the unityevents, why not just do that in OnDisable? And also if you are lazy loading the singleton with no way to check if it is valid outside of the singleton then you'll need to implement some way to check if it is valid if you need it to not lazy load in these situations
and if you need further help then you'll need to show the actual code
Still, the execution order is off. No point at using OnDisable in this case
you need to stop relying so much on the execution order
I know, i want to...
i gave you a suggestion as to how and you said there was no point. so at this point until you show code, i'm not going to bother providing any other advice since there's "no point" in following it apparently
There's no point in trying to help Wilhelm
Come on when did you become so full of grudges 
probably about the same time you decided you'd actively work against those who try to help you
what part of the execution order is "off". I looked in the other channel you posted it, and your screenshot only shows a bunch of logs saying "OnDestroy.." which just sounds more like you arent aware of the order
Everyone has the right to argue about something. Okey okey i will show the code wait a second
There's no point in having grudges
A note, you easily couldve gotten an answer 30 minutes ago if you just posted your actual issue rather than vague assumptions of how things work. It is always annoying when trying to help someone who hides their true issues, which you've seen in the whole last conversation
Unity 6000.0.2f1
https://paste.myst.rs/dvlrmxau
I hope my special issue will show itself to these scripting lords from this code piece. TryCreateSingleton() gets called because of Execution Order because SceneControllerPersistentSingleton.IsActiveSceneChanged returns false. Which makes _instance != null returns true in Awake() method of MonoBehaviourSingletonBase. Not happens always, sometimes.
so suddenly your issue is happening because of Awake? are you just going to change what the issue is until someone tells you something that you like instead of helping diagnose the actual issue?
Okay lets stop digital abuse and be real. Do you think the code itself has any problems?
how could i know when you can't even get the actual issue straight? not only that, but even if the issue were still somehow related to OnDestroy and an instance being created there, you didn't show real code that is affecting that, you showed your singleton implementation, but not the code where the issue is actually happening.
I exactly sent every single piece of code that creates the problem. It is in the link. I just prettied a little to make easier to read for you
no you didn't. you showed your shitty little test class which has nothing to do with the issue you are apparently experiencing, and the singleton implementation which does not create any instance inside of OnDestroy like you claimed was the issue
https://unity.huh.how/runtime-exceptions/nullreferenceexception
also !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.
What's the actual issue though? Is there an error?
Come onn i said from the beginning, my problem was execution order. You just wanted the code. Accessing a singleton from TestBehaviour.OnDestroy() triggers an error sometimes but as i said, it happens randomly. I cant give you an example that always happens. My exact problem here is execution order, not the singleton. I asked why would Execution Order does not respects? I actually testing while we are talking.
Accessing a singleton from TestBehaviour.OnDestroy() triggers an error sometimes
but you're literally not doing that in the code you provided
https://gdl.space/ihutejiwik.cs cardsdisplay
https://gdl.space/ixezoqemod.cs card
this is giving me this error and it is not loading the data about my chaos cards any reason why?
how can i fix this?
I know. This is because it is nothing more than calling any other singleton inside TestBehaviour.OnDestroy() that implemented MonoBehaviourSingletonBase
The error indicates you try to access an index in an array that doesn't exist
The error indicates what line of code has this issue
To fix, either ensure it stays in bounds using a check or fix the actual index
Idk what the index is supposed to be so can't help you there
So the error would seem to be this linecs cardImage.color = cardColours[(int)cardData.cardType[0]];
alright i'm not going to help you any further since you won't provide your actual fucking code that causes the error and you won't listen to advice about not relying so much on the execution order
how can i fix this?
To fix, either ensure it stays in bounds using a check or fix the actual index
Where either 0 index for card types is out of range or the index result cast to int is out of range
I'd say you log the index that you try to access and figure out why it's not the value you expect, or it's bigger than what the array allows
this problem is only happening when even there is a choas card in the scene other wise this error dose not happen
cardData.cardType[0] is returning an integer that cardColours does not includes. You may check cardColours for every scene
Do you understand the error though?
So does "chaos card" add a new card index that you try to retrieve here?
Because I assume your array just needs to be one index bigger
If you arent showing the actual problematic code, then you're still hiding the true issue and just showing what you assume to be wrong. Also ngl that code is unreadable on mobile, I had no clue what I was really supposed to look at.
Check if the card type array has at least one element - index 0.
Check if the card colors array has an index greater than the value acquired from card types of index 0.
Trust me, it couldnt be more obvious than that. I will send a bug ticket because i believe it is not my fault.
cartType has 7 entries, cardColours has 6
So as I mention, your array is too small
i am fucking dumb
thanks
u are a life saver
Well I just want you to understand the point of the error and what to look for, so hopefully that makes sense
Has the error been shown yet? I'm assuming they've got an "blah blah blah has been destroyed but you're still trying to access it" error.
as far as we know there's no actual error. it's just that their singleton gets recreated when accessed from OnDestroy sometimes. but they won't show the actual code that causes that to happen
thanks
nor will they listen to advice about how to prevent it
๐คทโโ๏ธ well I wont stop you. You didnt show any errors, seemingly removed the actual problematic code, and are asking about something that's not even true in unity. All of what you're asking is basically your assumptions at how things work, and not the actual issue at hand.
Cant imagine you'll get any better response from the people who will just tell you the order works as intended
Hell, I submitted a ticket for something that's actually a bug and the response back was "bug identified, will look into this" followed by "it's intended"
Guys i created a runtime terrain sculptor script with chatgpt but lowering just working on raised areas
i gave dozens of correction instructions but it just couldnt fix, what can be the problem ?
It just dont makes lowering under Z 0 position
I started to think problem is not script sided
here is the script
The problem is you're using a text generator for coding without knowing what you're doing. You won't really get help with AI code here. Did you add anything so it would actually go lower than 0?
omg, is this the future of programming? 'GPT didn't develop the code I wanted even though I asked it a lot, please help me'
why not working?
What's the error say?
because it's a plural
also unrelated to the actual error, but this will just assign this object's transform to the variable because GetComponentInChildren checks itself first
Yes as i said instructed it in many ways to go lower than 0
how do i fix that
just drag the reference into the inspector and remove that line entirely
ok thx
That doesnt matter. Did you yourself code anything for this logic? Because all it sounds like is you asked it a bunch of times to fix the code, blindly copy pasted and was shocked it didnt work
What debugging steps have you taken, you should have some clue at least where your errors lie
does anyone know how i can use occlusion culling on a terrain and the trees and grass painted on it?
this is a code channel
where should i ask
mb
I made this hundreds of times and made work all of my previous scripts
runtime level editor lowering feature just dont works
i even used few scripts from gitthub
default flat areas of terrain not being lowered
lowering code is just doing opposite of raising code
man, you are in the wrong server. we do not debug code for you that you cannot/willnot debug yourself
lol so what's this channel for ?
to help people help themselves
ridiculous
really? What is 'ridiculous' is your sense of over entitlement
entitlement ? yeah sure
@inland narwhal Once again. You should read #๐โcode-of-conduct and not post chat generated code to debug for you here.
Also if you are looking to argue about it, find another server. You already have a warning for off-topic.
Sure, I have no business left here already, never got help or progress
And for that you have no one to blame but yourself
didnt get help becaue you didnt ask for help
how do i reference a parameter in a script?
parameter ?
what is the easiest way to let a prefab change at the hierachie thingy
https://docs.unity3d.com/ScriptReference/Animator.html
look at the Get and Set methods
please elaborate
appreciate
(if i have my enemy on the field he can change the healthbar but as a prefab i cant connect the healthbar to the enemy script
I have seen the code for first time generated by chatgpt. Is that really ai generated.
When instantiating a prefab pass all the needed references.
no idea, he said it was and as he didn't bother to even post it correctly I never looked
well i cant reference it on the prefab and when i had it and then created a prefab the reference got deleted
That code looks simple but generating such logic in seconds by an ai. Thinking who wrote such ai Steve. That's marvelous.
did you try unpacking it
The script that does instantiation should provide the reference https://unity.huh.how/references/references-to-prefabs
no it is not. AI's don't write code, they string words together that just looks like code to trap the unwary or gullible
Scene objects can't be referenced by assets
hey the Animator.SetBool says to use "Animator.SetBool" in my script but the example doesnt even use Animator.SetBool
i get what to do though
just wanted to point it out
It does use it
It's not a static method
It's called from an instance
dont tell me, report the documentation, there is a button at the bottom of tjhe page
m_Animator in the example
i saw