#archived-code-general
1 messages ยท Page 154 of 1
delete all of that code
and use the event system stuff
such as what boxfriend just mentioned
which one
those have to be on monobehaviors, Im not in the context of a monobehavior here, Im in a POCO
for UI though looks like I will be forced to do event bubbling up, annoying but oh well
this is why when someone asks you why or what you are trying to do you should provide the full context
Your POCOs need to interact with MonoBehaviours to really interface with the game engine
yeah, I just try and avoid Inversion of Control unless 100% absolutely necessary
have a MB which gets the ui event and forwards it to your POCO
yep, that looks like what has to happen
inversion of control is one of the greatest superpowers you can do in programming. IDK why you hate it so much ๐
We've discussed this a little the other day
not the end of the world I just hate having to mix together Inversion of Control with normal direct composition
Obfuscation
SomeEvent?.Invoke(this, args)
Do you know what this will do? Do you have any easy way to tell at a glance in the IDE what this will actually invoke? You cant because you dunno if, or what, has subscribed to it until after its happened
It's a godsend that I don't know what it does
Thats why I hate events, you cant just F12 into em to be like "ah yeah it does precisely this"
I'm just announcing to the world that the player has died
i don't care what happens after that
yeah, it makes maint a living hell, speaking from experience
the stack traces are perfectly clean at runtime.
at runtime
exactly and what if you dont have the "runtime" :x
all I have to do is "Find references" and it will show me all the things that subscribe to it
And when you see that Foo is supposed to be subscribed to it, but on production for some reason the event is failing to do what you expect?
Then I add logs or debug statements to see when the subscription happens and when the event is invoked and quickly figure out the issue
You have no runtime, and you have no stack trace, you just have an error report from users that "When I do the thing the other thing doesnt happen... sometimes"
So you have to do an entire push cycle to production to get your log? :/
no i reproduce the issue locally
and if you cant?
at the core of it, events muck a lot up and make it hard to tell what is actually calling what, when you just have the code and no runtime from which the error was reported
Respectfully disagree, but to each their own
Sometimes though they are pretty much all you can do though, and it sucks but such is life
WOW guys, the solution earlier slightly helped ~10-20% but just using simple x,y,z int arguments instead of vectors for the addition reduced it down by ~80%
are you testing in release mode?
I gotta figure out now how to cleanly integrate these events with my loop that is already checking for other kinds of input
hey, i am creating a car game in unity and i've just made a car controller that follows a torque curve, has gears etc. and my question is on how i can get it to drift? i want it to be more realistic drifting than arcade drifting. i'm using wheel colliders, so i've tried making the extremum slip value less, which causes it to drift, but it is too "arcadey"
there are probably megabytes of whitepapers you can read on this topic
but i cant find any
yeah i've looked around quite a bit but i don't really understand how to implement it
same, judging by car controllers on asset store that are being developed for years and still feel off, this is a massive thing
probably the secrets to good physics are passed by studios inhouse
yeah, for example carx drift racing is made in unity and they have awesome drifting. but they probably have their own car physics instead of wheel colliders
dang i might have to buy this one
not if you dont want to reinvent the wheel sleeps knee
sleeps knee?
ahhh haha
https://www.youtube.com/watch?v=F0QwAhUnpr4 maybe, in the future
that looks awesome
oh shit, thats awesome
I know that you can pass messages into a WebGL unity instance and call functions on game objects, but can a WebGL unity instance send communication outwards to surrounding elements? For example, if scipt on the page could subscribe to events emitted by the unity instance?
you can call any javascript function you want from your Plugins js
which obviously can then do anything you wnt
Thanks for that. So just checking my understanding- let's say that I was looking to display a scoreboard outside of the unity instance. I have some html element set up outside of the instance, and within javascript bundled with the webgl build I could locate that element on the page and pass it data from the game by calling the javascript from the C# script. Is that the general idea?
C# calls javascript function and hands it game data, javascript function bundled with the game finds the element and populates it?
yep sounds about right
Ok, so I have a AI enemy, which is programmed to follow the player, I have a script which spawns them over time, the script uses instantiate to clone the enemy, the enemy being cloned is in the scene, because the player is in the scene, so it knows what to track, when that original enemy is killed, no more enemys can spawn, because the original is gone, what do i do?
Make the original a prefab
the original should never go away
and it should not be in the scene
it should just be a prefab
Simply drag the game object into a folder in the project window
And use that object in the folder as the original
Yeah but remeber if its a prefab then how does it get the players location
You give the spawner a reference to the player
the spawner gives it a reference to the player
Then the spawner will assign the player to the enemy ai script
Imagine this:
"Hello mr goblin. I have just summoned you. See that player over there? (points at the player) go kill him!"
but in code
yeah i been tryin that for an hour and havent got anywhere
IIRC someone walked you through it pretty in depth earlier
I know what i need to do, but not how to do it
it's only 5 or 6 lines of code tbh
yeah but he said i cant use anything that attempts to find the player
could you give me an example
it doesnt work
i still have a problem in the spawn script
public Enemy enemyPrefab; // assign in the inspector to the prefab from the project window
public Player player; // assign in the inspector to the player in the scene
void Spawn() {
Enemy newEnemy = Instantiate(enemyPrefab); //spawn new enemy
newEnemy.target = player; // give a reference to the player to the new enemy.
}```
this is pretty much it
the important bits
target?
this would be on the spawner script
a made up name for a field on the enemy script
that points to the player
presumably you have a field on the enemy script that you are trying to assign to point to the player
hmmm
on the enemy script you'd have like:
public Player target;
void Update() {
// move towards target here
}```
that's all
Transform would work as well, but is better to use something more explicit on your player though like a Player component
all monobehaviours scripts have access to their object's transform & gameobject anyway
sure
it said my enemy does not contain a definiton for player
yeah you have to write it
For example, I defined target here
ah ok
But I thought your enemy script already has something it's trying to move towards
Is there a list that can store multiple values within 1 variable
you should already have it defined
Yes you used it in your question
a List
there are actually many different collection types in C#
lists, arrays, dictionaries, hashsets
and many many more
you can even write your own
i meant a list that can store a float and bool at index 0
it does
yes a List
make a struct
or class
that contains a float and bool
and make a list of those
class MyClass {
float x;
bool y;
}
List<MyClass> myList;```
im saying that if the enemy is cloned(newEnemy), how would i acess newEnemy's Player Target
what do you think I was explaining to you earlier
I didn't wrrite all this just for fun: #archived-code-general message
try to remember
i have the prefab assinged, its whats in the script i need
you encountered the "how to locate things"
there are several ways to do that
all of them require a singleton in one form or another
the simplest way for you to achieve that, is to have a singleton that acts as a "service locator"
you already encountered such locators, for example GetComponent<T> is a service locator
which locates a component on a game object
in your case you need a global one
yeah but don told me not to use that because it takes away from performance
or at least scene scope one
Hi
you most likely misunderstood both what im saying and what someone else told you
I really want to learn how to use unity, I'm really looking forward to learn how to code
Do you have any recommendation?
start with isolated c#
visual studio, console application, do online pure c# tutorials
learn to make simple game in the console
learn basics of c# and programming
BroCode has an entire C# playlist that i would highly recommend
What?
bro what do you think my code example is doing
it;'s doing exactly what you're asking for
eh I would recommend the microsoft docs / website
also a great resource
docs is more useful for more advanced topics and the system namespace
Okay so basically I need to learn C#, I'll watch those resources!
you mean the API docs? cause their newer ones are getting more friendly and less Microsofty
After learning C# what's next
that was a huge turnoff for me in early days like XNA
learn the engine
unity learn has 750+ hours of high quality courses
4 free?
there is no way you'll ever end learning c#
it evolves every day
yes
cool
java, its basically the same thing
ew that's taking a step back imo xD
holy crap i did it
you never stop learning sure
Indeed
dont just learn the language, learn the fundamentals. that way whatever you learn in C# you can apply in other languages
but jumping into unity is akin to accelerating a car in 5th gear
#๐ปโcode-beginner message
here a tutorial dump. also, start in #๐ปโcode-beginner, there are tutorials linked in the pins from there . . .
@ashen yoke i used GetComponent to get acess the the player transform
is that what u meatn
GetComponent was an example of what i was talking about
https://unity.huh.how/programming/references
next level upgrade, read this
GameObject newEnemy = Instantiate(enemy, new Vector3(Random.Range(-5f, 5), Random.Range(-6f, 6f), 1), Quaternion.identity);
newEnemy.GetComponent<EnemyAi>().target = player;
you can spawnin enemy as EnemyAi
and skip GetComponent
EnemyAi newEnemy = Instantiate(enemy, new Vector3(Random.Range(-5f, 5), Random.Range(-6f, 6f), 1), Quaternion.identity); newEnemy.target = player;
Does OnPointerExit always fire off before OnPointerEnter for 2 different objects?
In my experience, yes
the hell is a singleton
Lets say I have 2 gameobjects touching side to side, no gap, and mouse is hovering over A atm, it leaves A to hover over B, causing both PointerExit for A and PointerEnter for B, is it actually safe to rely on PointerExit firing first?
if i try newEnemy.target = player; it gives me this
Well that answers that, perfect haha, thanks!
Change the type of enemy to your enemy class instead of GameObject
doesnt work either
can you show what you have right now?
you're not accessing .target on EnemyAi and instead trying to do it on GameObject for some reason.
at least that's what error seems to say
๐ Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
a powerful website for storing and sharing text and code snippets. completely free and open source.
holy shit this code formatting..
why did you remove GetComponent<EnemyAi >
if you gonna remove it you gotta use it like i said earlier
you'd have to change Both GameObject to EnemyAi
if (GameObject.FindGameObjectsWithTag("Enemy").Length < 10)
You could probably store enemies in a List instead of doing this every spawn
but you probably haven't used list before ๐
yeah the other thing didnt work
it does work
the enemys just stand still and wont clone
i will just use get component for now if that ok
the getcomponent has nothing to do with your issue
you will see the same issue.. it's something else
show me which line you tried that didn't work
still dubious that's what did it
spawning as EnemyAi is the same exact thing.
i am cloning a prefab, which is what enemyPrefab, and you told me to change the from gameobject to the enemyai class from the other script
it will not know what to spawn
I been doing this for years, I'm sure I know how it works lol
here i send you what works and what doesnt, ok?
your spawning is just weird to me
sure
I bet you didn't change one of the types, particularly the method parameter
probably getting NRE not even realizing
a powerful website for storing and sharing text and code snippets. completely free and open source.
work perfectly fine
ok now the broken one ๐ฅ
a powerful website for storing and sharing text and code snippets. completely free and open source.
Ah thats why
you had to remove the old prefab
it still had it stored as GameObject
lemme try
haha yeah forgot that bit .. haven't used GameObject type in ages
you're just specifying the type , class is a type . GameObject is also a class
so it just spawns whats attached to the script?
so yes?
i should prob remove the serialized field and make it private so i dont get confused
Should i*
no because you won't have a way to set the prefab of that type
but it is just set to none
which field are you referring to?
oh wait i can select the script
you drag in the prefab that has that script yes
if it is set to none will it apply to all gameobjects with the script?
ignore the weird prefab name
if it's set to blank you're just gonna get a NullReferenceException
I'm confused wat you're asking, why would you set it to blank.
esp if it's working now
oh ok ๐
wait
the prefab not in the scene doesnt show up in the assets area for the selection but if i drag and drop it it works, ???
Prefabs don't need to be in the scene, which is one of their benefits. Think of them as blueprints, or templates
By assets area do you mean hierarchy? it should be in the project window where assets are. Where else would you drag and drop it from?
look
however i can still drag and drop a prefab in
and it works
could be a bug
idc tho
is your field GameObject? or something else
Honestly, I've never seen that Assets window before. So I have no idea lmao. Feel dumb right now
If it's in the project window, you're fine.
because this menu notoriously is unable to find components on prefabs - it can only find root level objects in the assets folder
Yeah, it's gameobject
I could never get that thing to find prefabs in assets folder even though it has that button for it
navarone do u make games
its so annoying
i make prototypes mostly or tutorials on YT hehe
sometimes jams
unfortunately unity says this box failing to find objects is "by design" becaues apparently it would be too performance heavy..?!?!?!
yes
and early versions of QuickSearch are showing why
you have to scan/cache everything in every prefab in the project for it to work
if you dont do that you have to go through all the prefabs every search, loading them all into memory
the thing is is - id rather it be slow than not work at all. id rather have unity hang up for 1000 ms than search for the asset i want by hand which would take 20 times longer
quicksearch package is a thing
argument on what
you wanted a feature by unity, you got it
made by unity
Quick Search
does quick search fix the asset box not finding every object?
Link?
profile
i read the docs. and the answer is "no it doesn't" lol
in an unrelated note. has anyone had this issue about OnValidate()? i have an scriptableobject that uses OnValidate, and it works perfectly fine in the editor. but for some reason when i build my game, the fields of the scriptable object that i populate in OnValidate() aren't being serialized.
i found this thread online
but their issue was that they weren't using [SerializeField]
but im definitely using serializefield, so im not sure if this issue is related
so it works, finds components in prefabs
with limitations but it works
it's a good replacement functionality, but it still doesn't fix the asset box in the object picker. i dont know why they dont just use quicksearch's code to replace the broken code in the object picker
you are modifying an SO in editor in OnValidate, after you do that you have to SetDirty
any non inspector changes that arent done on serializedProperty wont be saved unless you mark the object as dirty and then save project
they wont do that because its slow
i will try using SetDirty, thanks
they wont disrupt workflow for thousands of users with something that has the potential to slow the whole thing to a crawl
i dont see how it would be any different than using quicksearch other than the button being in a different place
yes it wont be, thats why quick search is available for you to use, if you need that functionality use quick search
this gives you and everyone a choice, use default fast way to access data that works for most cases, or if you need to do slow search use quicksearch
use the default fast way when it actually works (textures, prefabs, etc) and default to using quicksearch when the field type is a component (instead of failing to find anything)
so install quick search and use it for finding components?
youve never used it, so you assume its going to work same way as default one
it doesnt, every time a change is made to anything it scans objects to build the cache
its not just slow when you press a button to open something, it slows down the whole workflow
it affects you even when you are not searching
and to me it doesnt look like an issue that can be solved easily, unless they manage to integrate it into native code
idk about you but im running 2022.2.8f1 and i have quicksearch available but its not in my package manager
did they make it included by default?
i mean maybe theres a way to disable it but its not a package anymore
wait wait wait
does this do what i think it does
Initially released in version 2021.1, Search has since become a core workflow
so yeah they moved it to core
well problem solved
my current project isnt really big enough to be slowed down but do people experience issues with quicksearch?
i only tested early versions and they slowed everything down dramatically
when i did this just now it stopped for a second the first time i searched for this type, but after the first time searching is instant
indexing prob
Hey navarone i had the same prob with some score text and having the prefab have the text assigned and i got it to work with my prior knowledge
Is there a name or term for Unity's GameObject-MonoBehaviour paradigm
OOP? composition?
I guess composition works
I used to think it was some sort of butchered ECS paradigm
Then they added the real ECS
Maybe it's just Entity-Component
It is the same code?
If you don't put braces {}, the if statement only covers the first line after that
Better to use braces to avoid silly mistakes
Correct
Right now they're the same
But if you wanted to also have the debug.log be covered by the if statement, you need to wrap both lines in braces
I hope you understand
Yeah, thank you
You're welcome
It is a sort of butchered ecs paradigm 
Once you go the route of having managers manually update monos you get close to ecs
We have a system like this, but with jobs and a custom player loop. In terms of performance its close to ECS, the only downside is getting the data back to the monos or god forbid destroying more than 500 per frame
But pools fixed that for the most part
is there any method that's called in DDOL when scene is changed?
or do I call smth manually?
oh, wait, no, I don't even need it
if I have 2 same ddols, then 1 will call Awake
and I can do everything there
nice
Pretty sure you can look up how to detect when scene is changed. It's a callback
It being a DDOL object is irrelevant
yeah, I just can do it when I change scene
but it doesn't matter
I just do everything in Awake
private void Awake()
{
if (!GameObject.FindGameObjectWithTag("#ScriptsHolder"))
DontDestroyOnLoad(gameObject);
else
Destroy(gameObject);
}
This really seems like you should just use the singleton pattern instead of Find
what kind of pattern are you talking about?
Unity singleton
wdym? it's a common thing todo with Singleton pattern
nah, I think find if better in my case
also #ScriptsHolder has multiple scripts
yet again in your snnippet you're only looking for 1 of them, no?
1 of what?
oh, scripts
I see
nah
I has 2 scripts
I just have to disable that gameObject
If you have issues with retaining gameobjects depending on what happends in your game, then maybe it's a good idea to create a dependency system that tracks certain lifetimes. I always create a manager that tracks gameobjects that should only appear once and persist through scene changes, but also tracks gameobjects that should be recreated when a scene has changed. You can then just request a dependency from that manager, instead of trying to find it yourself.
no, I just have host and normal scenes
I want to have #ScriptsHolder is host mini game engine to create levels (that just I can create for now) and also in MainMenu that's available for players
anyone got a moment?
im having trouble assigning proper rotation angles to 2d npcs...
here's part of the code that handles it
else // if (rot_type == "move_DIR")
{
if( !spawn_angle)
{
Debug.Log("spawn_angle");
direction = new Vector3( transform.position.x + Random.Range(-1f, 1f), transform.position.y + Random.Range(-1f, 1f), 0f);
prev_direction = direction;
spawn_angle = true;
}
else
{
Vector2 movementDirection = rb.velocity.normalized;
if (rb.velocity != Vector2.zero)
{
direction = new Vector3(movementDirection.x, movementDirection.y, 0f);
prev_direction = direction;
}
}
}
float rotation_speed = 10f; // og
direction = direction.normalized * 1.1f;
Quaternion targetRotation = Quaternion.LookRotation(Vector3.forward, direction);
rb.rotation = Mathf.LerpAngle(Prev_rotation, targetRotation.eulerAngles.z, rotation_speed * Time.deltaTime);
Prev_rotation = rb.rotation;```
what doesnt work is the spawn_angle part
while it runs one time, the direction isnt properly set, the rest of it seems to work ok
hmmm, can anyone help me about procedural meshes? I know how to create them from triangles, but I am in a need for an algo, that finds those triangles out of a shape, that can be concave as well as convex...
I usually don't use braces myself for if statements
But I suggest if you want to do that and if ur "Fairly new" to keep them on 1 line with the if statement for now (If you plan to not use braces)
how is this not working
"the name test does not exist in the current context"
No, I can't reference anything
I could reference stuff in other scripts, but now when I made this new one, nothing works.
Code logic has to go inside of functions.
You may want to do some tutorials on basic coding.
And where is the function that you're calling?
above sellallfish
Share your code so we don't have to use our imaginations.
Excuse me?
Not sure what part was confusing by that statement
public void FunctionTest()
{
}
public void SellAllFish()
{
FunctionTest();
}```
Share your code? You've already demonstrated some lack of basic understanding of coding, so just want to make sure the code actually is correct.
And what's the error that it's giving you?
I know how to code. My Visual Studio is having problems with referencing
If it's a VS issue, make sure it's configured: !ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
"The name 'FunctionTest' does not exist in the current context'
I'll try that out
Hello, let's image I have a game, where I create levels. Should I have 1 json file to save all levels e.g. Levels or seperate json file for each level e.g. Level1, Level2, Level128?
Share your whole script properly.
!code
๐ Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
What are these levels?
What data about them do you need saved?
for now I just save prefab, name and position
you can just do 1.. it's a matter of how you'd structure your data
What are these prefabs? Characters? Items?
I create mini game engine to create levels
also depends, sometimes it's needed for them to be saved separately. Also depends on the scale of your game
you can create levels for e.g. geometry dash, if you know this game
Then it's probably better to save them as separate files? Especially if you expect users to be able to view and edit them.
no, users won't be able to edit json files directly
they are not programmers
You don't need to be a programmer to edit a text file.
they will enter game and drag prefabs
it's not that easy and comfortable
Then it doesn't really matter how you save them.
probably in 1 json file that contains all levels
and each user should have this json file
but for now just me
The next question is: where do I save json files for my game
I think I shouldn't save all those files on my pc
like database probably?
Wherever you want. But there is the unity provided persistent data(I think ๐ค) path that is recommended.
persistent data is probably PlayerPrefs..
Oh, was cloud an option?๐
it's absolutely not reliable
I dunno.
No. That's the registry. You shouldn't save there.
I have never worked with clouds or databases
they, that's what I meant.
I just wanted to ask where those things are done.
e.g. I have 1000 players in my game and all they have made multiple levels
and I should save all their levels in jsons
You need to decide whether you want the players to save data locally, or upload it somewhere.
they'll save data locally
they create level and it's automatically saved
Then in the persistent data path is good enough.
Regardless, you would still probably want these as separate files. That way it can be easily uploaded/downloaded and a corrupt file wont nuke the whole other 999
yes, I mean each player will have their json file Levels.json and this file will contain Level1, Level2... Level457
like probably foobar123.json
Storing it in 1 is risky, and really just more work
so 1 json file for every level?
When you make a level, you'll need to edit that json rather than making a new file. If someones file gets corrupt they lose out on 1000 levels rather than 1
oh, yeah, you're right
I haven't thought about that
but still I have to save them somewhere..
And when its uploaded by a user anyways, itll just be a file containing only their level. So itll already be an individual file, you would just be copying it to 1 for almost no reason
The persistent data path
Then just make sure the names are unique
You could even just prefix them with an index plus the name the user actually gave, which would solve the issue of duplicate names
yes, but where should I save them?
I don't think I should save them all on my pc
or should i..?
Well you'll need to download the actual level if you want to play it
But depends on the game where you want to store every single level
Steam has it's own workshop where users can upload stuff like this
I dont know much about alternatives
it stores levels on my pc, right?
if so.
let's imagine users have created 1.000.000 levels and all they are stored on my pc
Well a user wouldnt upload a file and have it immediately download on your pc
what if you lose level 2 and 5 while the game itself needs for them to be existed otherwise it won't load 
on my pc.
You would use steam workshop or whatever alternative you find, and only download the ones u want to play
which technically has the same limitation as having single (1) file ๐
Why should I download them?
Why do you need these files on your PC..?๐ค
๐คทโโ๏ธ hes talking about user made levels, I doubt a user made level is critical to the story.
I don't need them, that's what I am talking about
How are you going to play a level if it's not on your pc?? I'm saying you would download the ones you want to play
that's not what I mean, I mean on host's pc
admin's
If I have created a game, then I'm host
and there are other players that create levels
This is once again having a giant nonsense convo that stems from the fact you barely explained what exactly you meant before you started
People can't give you advice if you just ask something vague and then say "no not like that" over and over again
haven't I?
Where do you want these files stored and why?
I really have no clue what this means. These messages imply your users are creating 1000 levels while connected to you via networking
But I know that's not the case
it's just moving the goalposts, but completely out of ignorance instead of argument
Hello, let's image I have a game, where I create levels. Should I have 1 json file to save all levels e.g. Levels or seperate json file for each level e.g. Level1, Level2, Level128?
You create levels?
No, the users are creating levels!
Saving them?
No, this is over the network!
Where does it start and end??
I create my game and I make players of my game to be able to create levels.
apple123 can download my game and start creating 3 levels. also other 1000 users start creating levels.
Every time those users enter the game, they can see what levels they have created.
They can post their levels for others to be able to download and play them.
So let's imagine there are 5000 levels created by users in total.
These levels should be saved somewhere, the same like all my scripts that I have created are save on my pc somewhere in Assets file.
Where are all those levels saved? Should they also be saved on my pc and when player wants to play a specific level, they should download it on their pc too?
I really hope I have succeeded in explaining it
They are saved only where they are needed to be saved. If a player wants to know about the levels they created, then they probably will have them on their computer, as with anything they downloaded. If a user wants to post a level, then it's uploaded to a server.
that's what I wanted to hear. What kind of server?
๐
like maybe I should use database to save all users data and their levels...
probably that's what I need
is it most commonly used database for unity?
Nobody would know the answer to that
I see, is it reliable to use with unity?
It works with Unity ๐คทโโ๏ธ
Maybe do some research and look at your options.
Literally any database service you can think of is reliable
If it's just a server for storing json, itd have no effect if this was unity, python, or anything
I see, thank you, I just wanted to ask advice of people that have used databases for networking
cuz I have never
I'd say the most common would still probably be steam, with its workshop
Or at least the most well known
If this is the first proper game you've made, it sounds very overscoped
what does sound overscoped? ๐ค
_this time will be different _
Surely I can do everything I ever wanted in this game
Learning development + unity + databases + multiplayer
Wait hols up authentication
I cannot do now, but making this game will definitely take some time for me
You didn't know how to save a file yesterday, and found it difficult to research, I don't know how you're gonna figure out a database
and this time will be enough to learn
limited scope is always good idea
I've been coding for 9 years, and I can proudly say i too have over scoped my project by trying to make a multiplayer physics game.
Its never enough time with learning multiplayer
I have already written a script to save all info about level and then paste all gameObjects yesterday, even though I had no clue how to do it
Or networking stuff in general
also I have almost not worked with json before
I have summer holidays, should be enough
yeah, maybe I will be working for 9 years on this project, who knows
Your first project should ideally be extremely short, designed to be throwaway, a learning opportunity and nothing more
that's not my first project.
I had some little projects before
can anyone tell why this given no error and dosnt work at the same time ? using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameOver : MonoBehaviour
{
private AudioSource audioSource;
public void start()
{
audioSource = GetComponent<AudioSource>();
}
// This function is called when the player collides with the trigger object.
private void OnTriggerEnter2D(Collider2D other)
{
// Check if the colliding object is the player (you can use tags or layers to identify the player).
if (other.CompareTag("Obstacle"))
{
Debug.Log("Collision");
audioSource.Play();
Destroy(gameObject);
Invoke("Restart", 1.5f);
}
}
public void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
Whatever it is, it's one of your first
Start should be capitalised
!code also?
and yea idk those website for code pasting... they just doesnt work
๐ Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
There's many options, if one of them is broken use another
yeah, that's why I am not making my own game engine
ok thanks... btw if start doesnt run and the code will not execute further ?
tried every single one
yes
ok thanks
Then you're not using them properly. Paste your code, click save, then copy-paste the URL
oh ahem
Only Start will not run. The rest of the code will run if the component has been placed on an object.
If you are not getting OnTriggerEnter2D then there's debugging for physics messages pinned to #๐ปโcode-beginner
Well, looking at it again it seems extremely flawed. You destroy this gameobject, which has everything on it. It'd destroy the object and then immediately halt everything else you're trying to do
when it collides with objects neither it gets destroyed nor the message comes in console
I mean its not colliding
but it seems to be colliding in the play mode
Did you go through the #๐ปโcode-beginner resource? You're also using a trigger, so it won't physically collide, just pass through
yeah but nothing works\
btw does this have problem with that ?
objects are not on the same axis on z axis
@quartz folio
The Z axis doesn't matter
hm ok
Hi! I have a problem with limiting drag distance in my darg and snap script. The script is not limiting the drag distance but placeing the object to the player with the distance of maxDistance also it's made to work for multiplayer. here is the script: https://pastebin.com/MKaeEzeD
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.
Can anyone help me?
please
im stuck on this thing for 2 weeks
umm... I removed everything and this is the script now... but this is also not working https://paste.ofcode.org/cw6YrXnT6u6qBna6yFuJc3
You went through the troubleshooting physics messages resource? If so, show the objects in question
Why are you looking at collision messages if you are using a trigger message?
?
Trigger
wow.. nice.. well that dumb I am
But like, if you thought you were using a collision message then you would see from that page that what you'd written was wrong, and you would change it to match the collision setup
no.. I was lokkin into that
collision
Collision2D collison
to check if thats correct
well new problem... Collision doesnt contain CompaerTag
collision.collider
ok thanks
a loop
private void Repeat()
{
int timesToRepeat = 8;
for (int i = 0; i < timesToRepeat; i++)
{
Debug.Log("Repeat only certain amount");
}
while (true)
{
Debug.Log("Some infinite loop");
}
}```
is just an example, yeah why would it not work if you reset scene
do you plan on using this for an enemy spawner?
you should probably put it in a coroutine with a timer
it worked finally hehe
bool spawningEnemies = true;
float timeTillNextSpawn = 1;
private IEnumerator Repeat()
{
while (spawningEnemies)
{
yield return new WaitForSeconds(timeTillNextSpawn);
//spawn
}
}```
what happened to scripts-only build in late unity versions?
I was under the impression it got integrated to the standard 'build' system when development mode flag was checked, but this doesn't seem to be the case (?)
Hey guys I am trying to generate a board at runtime that has different sprites assigned each square using the same prefab. It works but it is overlapping. I had a method when the the prefab sprite was not null but it doesn't work anymore to space properly next to each other. ```void GenerateGrid()
{
Vector3 boardPosition = transform.position; // Get the position of the Board object
float squareSize = squarePrefab.GetComponent<SpriteRenderer>().bounds.size.x; // Get the size of the square prefab
for (int x = 0; x < gridSize; x++)
{
for (int y = 0; y < gridSize; y++)
{
Vector3 spawnPosition = boardPosition + new Vector3(x * squareSize, y * squareSize, 0f); // Calculate the spawn position relative to the Board object
GameObject squareObject = Instantiate(squarePrefab, spawnPosition, Quaternion.identity);
squareObject.transform.parent = transform; // Parent the square object to the board object
}
}
}``` I tried adding a coroutine but I don't think I got it right
Looks fine to me, on what axis are the sprites overlapping?
Also you can pass the parent transform as a parameter to instantiate
I am currently not using the above code since the prefab is null at run time
It doesn't seem to work anymore
Since it can't get the sprite size
Okay then its probably ran before the sprite gets assigned right?
Are all the sprites the same size?
Because they look like different sizes
If you are not using the code above, then you should probably post the code you are using now
how can i determine the .net framework a unity mono game uses?
{
StartCoroutine(GenerateGrid());
}
IEnumerator GenerateGrid()
{
// Wait until the SpriteRenderer component and its sprite property are not null
while (fieldPrefab.GetComponent<SpriteRenderer>() == null || fieldPrefab.GetComponent<SpriteRenderer>().sprite == null)
{
yield return null;
}...// Calculate the size of each field based on the size of the sprite and the scale of the prefab
float fieldSize = fieldPrefab.GetComponent<SpriteRenderer>().sprite.rect.width * fieldPrefab.transform.localScale.x;
// Instantiate the fields on the game board
for (int x = 0; x < boardLayout.GetLength(0); x++)
{
for (int y = 0; y < boardLayout.GetLength(1); y++)
{
FieldType fieldType = this.board.GetFieldTypeAt(x, y);
Vector3 position = new Vector3(x * fieldSize, y * fieldSize, 0f);
GameObject instance = Instantiate(fieldPrefab, position, Quaternion.identity) as GameObject;
instance.transform.SetParent(boardHolder);
instance.GetComponent<SpriteRenderer>().sprite = fieldType.Sprite;
}
}```
Oh
How is fieldPrefab being set?
{
public GameObject fieldPrefab;
public Transform boardHolder;```
Set from the insepctor?
Aha
You are referencing your prefab asset and not an instance for the prefab
So whatever sprite you load into the prefab at design time gets used for the bounds calculation
You should instantiate a prefab for every cell in your grid
And you can just pick the first one for the size of the sprite
So if you add a fieldSize = instance.GetComponent<SpriteRenderer>.bounds.size.x in there it should work
Hey thanks a lot for all this info! I will go try it
Remove the coroutine
And the while check for the null
And set the fieldsize to 0 initially
Worked like a charm
is it possible?
@plain nebula

Now help me develop the rest of the game @winged mortar
what exactly doesn't work ?
thanks, im trying to get it from a different mono game
We dont do decompilation / modding here
Hello, when using Application.persistentDataPath i get an error about the permissions of the creating another file using :
FileStream stream = new FileStream(path, FileMode.Create);
EntityData data = new EntityData(player);
in the ,,DefaultCompany" folder.
i would instead want to make the pathing another, like using a string from code and make it universal since i cannot for the life of me find the issue (yes i set the permission of the folder to everyone, no i don't have spaces).
So how would i go about creating a universal file path? without using ,,Application" class
im sick of trying to solve this at this point
how and where are you calling this method ?
Yeah sure man I have a time slot available in about 60 years, that sound cool?
function?
Might sound weird but could you try opening unity editor as an administrator?
It could also be that your path is too long
are you getting an error or?
show error
It might also be worth trying to build your game and run that as administrator
how
this should not be a solution
having to tell all players to switch to admin to run game is silly
but the editor doesn't support administartor as i know
Its not but it can help identify the problem ;)
this means u forgot the file extension
nothign wrong here btw?
public static void initializePaths()
{
paths[0] = "/saveFile1.txt";
paths[1] = "/saveFile2.txt";
}
then you should be inside #๐ปโcode-beginner
same error
lemme send full code
ok?
you're using Shatterd_Worlds Aprat
?
๐ Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I see the folders
static string[] paths = new string[10];
public static void initializePaths()
{
paths[0] = "/saveFile1.txt";
paths[1] = "/saveFile2.txt";
}
public static void save(Player player, int saveID)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + paths[1];
FileStream stream = new FileStream(path, FileMode.Create);
EntityData data = new EntityData(player);
formatter.Serialize(stream, data);
stream.Close();
}
sorry but i like discord's code conv xd
is this the only save method you have?
Also combine paths using https://learn.microsoft.com/en-us/dotnet/api/system.io.path.join?view=net-7.0
i got paths[1] because i wanted to test
Or Path.Combine
which path gives you error
paths[1] = "/saveFile2.txt";
where do you call initializePaths
I-
and save
nicee
lemme see now
so a null destination
Just do this next time man @mossy shard
int[] array1 = new int[] { 1, 3, 5, 7, 9 };
No method required
you can also just do
private static string[] paths = new string[]
{
"saveFile1.dat", "saveFile2.dat"
}
beat me to it
yes true thx
it was just testing bro
will do this for the final product
@rigid island ehm
is this normal
for a binary file yes
yea you're trying to serialize a GameObject?
ye
wait i made it binary?
yeah not really good to serialize though
also don't use BinaryFormatter
what then
what is EntityData
depending on how complex it is you might just get away with plain text
ideally you want to serialize something easily serializable
if it's really simple just use newtonsoft.json
player inv, stats, points, position, lvl, cosmetics
but i got mostly commented out for only position so i could test
btw
why this happens?
can you upload your entity data class
idk I don't use binary formatter lol
probably something to do with what you're serializing a whole gameobject which isn't very good
public float[] position;
public EntityData(Entity entity)
{
position = new float[3];
position[0] = entity.transform.position.x;
position[1] = entity.transform.position.y;
position[2] = entity.transform.position.z;
}
i suggest you format it into JSON or something
this is what i am saving
i had my Filstream to Create mode instead of open
ig this is this issue
yeah check this video https://www.youtube.com/watch?v=mntS45g8OK4
wouldn't that pe very delicate for like changing the in game stats>
funny enough my video also uses generics
yeah i saw your channel too
yes, anything on the client can be changed
ye exactly
but do you really care what players change in their own game?
yes
You cant realistically stop that @mossy shard
eh, if game is single player who cares how they play their game
in my experience, you shouldn't worry about that until it becomes a problem
most people literally do not care about cheating
w
sorry misstyped
shouldn't you worry about something if it becomes a problem
isn't it like common sense
Even if it looks like garbage when openining it in notepad, people will just decompile your game and look at the classes that go into the binaryformatter and redo do it
anyways lemme see if it works now
There's so many save editors for games
do i count?
now i am just using admin commands
wait
why did i respond to you
i wanted to respond to myself
sorry
@rigid island @winged mortar @white gyro thanksss, everything works now
i will think abt that
I didnt do anything but you are welcome 
does Invoke let you call a function delayed by one frame rather than a time in seconds?
are you talking about the Unity's Invoke ?
okay so I just downloaded an endless runner template from Unity and after playing around and adding a few things I thought I would change the art but for the life of me I could not figure out how, I don't really know what screen shots would help but if anyone knows how to do this any advise would be apperciated!
is there a method similar to Physics2D.OverlapCircleAll that just finds what is overlapping with the collider? I'm sure I am overthinking this, massively, and I could probably just do something with "onCollisionEnter" but, yeah
Hi everyone!
So I'm making a splitscreen multiplayer game and I was wondering how can I go about making a spawn system when a player joins instead of the players spawning on top of eachother?
hmm it seems there is an overlapCollider method, but it works way differently. Wish there was just an overlapColliderAll method
this is such a weird way to do it, this method uses a list as a parameter, then stores the results in that list. Instead of letting you just set a new list equal to the results
Itโs more efficient that way, since it lets you reuse the same list over and over
it's not weird at all
I guess, but it works so different than the other ones
where you just define the list equal to what overlaps the square, or circle, or whatever shape you are using
They have NonAlloc counterparts that behave the same way https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircleNonAlloc.html
Need some help: https://hatebin.com/pemamianrg
I want to make a collection of delegates that has a generic type.
so I can just create an empty list at the start, and then use it for this?
nvm i just changed the delegate to public delegate void EventHandlerWithParam(IEvent evt); and used that for the list
ok stupid question because I am having a brain fart
trying to think of how to word it though
ok so i have "private List<Collider2D> results;" do I need to give this a value before I can use it in that method? I know this is probably like, a really , really dumb question im sorry
Which function are you using?
you want to create a list yes
private List<Collider2D> results = new();
ok like, how do i word this
otherwise there is no list
if it was public you wouldn't need to do this because Unity would create it for you
(I'm not recommending you make it public, just explaining)
I just havent coded in a little over a year, so im having a few dumb dumb moments lol
Hey guys, I need help
I have created a small demo in Unity 2d, but when trying to destroy the game objects (basic game logic is - destroy moving objects)that are moving from above - on trigger enter is not destroy it. Looks like it's not on a similar layer. Does someone has similar issue?
sounds like an issue with your basic setup and/or code
the https://forum.unity.com/threads/why-ontriggerenter2d-doesnt-work.1463648/ - I have made a post on forum maybe you can check - there more info
Here is screenshots from the project
Ok I'm back to square one.
(original issue: https://hatebin.com/pemamianrg)
full script: https://hatebin.com/sqjqjjslta
๐ Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
wait maybe i just need to cast the event handler
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
nope didn't work
and and which object is this script on and can you show the interaction where this isn't working?
Bomb has trigger, and the enemy does not. Is bomb working as expected?
They both have the detect collisions script though
are they ever actually touching each other?
Are those prefabs ever instantiated?
What's going on
the collider radius seems pretty small, for example
make sure the colliders are actually overlapping
I dunno. It's Vova's game.
I just noticed they both have the script with OnTriggerEnter attached even though only one is a trigger.
And yeah the colliders are really small. Noticed that too.
Yes, they all prefabs - bomb is trigger. After bomb touch Enemy - enemy must be destroyed
Does the bomb destroy itself? And the enemy remains? Or nothing happens
show what happens when the game is actually running
show the objects actually overlapping
and the inspectors of those objects at runtime
That's how it's looking - looks like enemy layer is above bomb layer and trigger can't see it. I have already increased radius, but it's still same
@leaden ice Any ideas?
make sure:
at least one needs to have a rigidbody, ideally both
both are the 2D versions of colliders
make sure you're using OnTriggerEnter2D not OnCollisionEnter2D
Make sure the OnTriggerEnter2D code is on the object with the trigger collider (I think that's required?)
ah you posted screenshots earlier, didn't notice
those objects are quite small and moving really fast
I wouldn';t be surprised if:
- they are simply never overlapping due to speed and small collider size
- they are never overlapping because the colliders aren't lined up with the sprites
what layers are the objects on and how is your collision matrix in the 2d settings set up?
@dull thorn in your OnTriggerEnter2D method, add a line like this
Debug.Log("Collision: " + gameObject.name + " with " + other.gameObject.name);
and show if console says anything
now show the collision matrix
it's in Edit->Project Settings->Physics, it's called Layer Collision Matrix, and it's at the very bottom
https://paste.ofcode.org/WnWSpERDsazSPv7Ba9Mc6h ... why cant I jump ?
If I remove the boolean condition for jump then I can jum[ even in air
but I want that I can jump only when ongorund
but that way it doesnt even work
does ground object have the correct layer
It have Ground Layer and Player have Player layer
is this from plai's tutorial?
after 3 frames into a jump, your jump velocity is 12.5% of your initial velocity. If you have gravity turned on, no way you see that.
no
then i dont know, apologies
wait maybe.. I forgot the name
@dull thorn matrix looks good, now try this debug log thing
if it is, i was in his server and let me tell you half the people who joined there were all asking the same question as you, 90% of the time me and other people couldnt fix the issue
goes above my head ๐
void Start()
{
LayerMask _ignoreMe = LayerMask.GetMask("Player");
}```
Why do you have that first `LayerMask` in there?
Nothing
use AddForce instead of setting the velocity
So is there any other method to achive this.. agood and practical one ?
id search for another tutorial tbh lol, id be way too lazy to figure it out on my own
to exclude the player layer.. so that script doesnt detect the players collider
ok
ok xD
btw everthings works ... I can jump even in air if I remove the start method and Second line of Update
Not what I askedโฆ adding that LayerMask type to _ignoreMe inside a method causes it to become a local variable meaning it doesnโt exist outside of that method.
try turning both into non-trigger colliders, and switch to using OnCollisionEnter2D, just for a test. Also make sure both rigidbodies have collision detection set to synchronous, and have "simulated" enabled - in case you're not using the rigidbodies to move.
ohk
You should also negate/invert the layermask as well. Otherwise it will only hit stuff on the โplayerโ layer
how Do I do that ?
https://unity.huh.how/programming/physics/bitmasks
Find out how to invert a layer mask
ok
and that they arent static, and if that doesn't work turn on the option to never sleep
this is quite a weird problem tbh
btw If I do it outside of a method then unity gives error thats why I did that
Yes that makes sense
that's not the point
in your start method, you have
LayerMask _ignoreMe = LayerMask.GetMask("Player");
this overrides the global _ignoreMe, and makes the new value usable only in that function
you should instead change the global _ignoreMe, like this
_ignoreMe = LayerMask.GetMask("Player");
LayerMask a;
LayerMask b;
void Start()
{
LayerMask a = GetMask(); // creates a local variable and doesnโt modify the global one
b = GetMask(); // actually modifies the layer mask variable
}```
that said, yes - in the way it's currently set up, it'll only detect the player
@wintry crescent rigidbodies have collision detection set to synchronous - how to make it?
I hate the kind of bug where its the king of bug where it seems like this should have already presented itself as a problem, but hasn't
setting in rigidbody I believe
continous, sorry
not synchronous
I cant define LayerMask a; outside of start otherwise it give error
you can define it outside of the function. You can't set it with code outside the function. You need to put the declaration (private LayerMask _ignoreMe;) outside of the function, like you did, then you need to set it (_ignoreMe = LayerMask.GetMask("Player");) inside a function
Itโs an example, do you understand what i mean by local and global variables?
ok
yes ik now
When you are finished, we can invert the layermask
I have a list of transforms for check points for where I want my Ai to go using navmesh. Im trying to make it so when i pick a transform from the list at random I can also check a bool to see if the checkpoint is taken already im really struggling on how this would work please help if you can ๐
ok
like this :- ~_ignoreMe
@wintry crescent It's works)
Yes, you should do it when you get your mask
void Start()
{
blah = ~LayerMask.GetMask();
}```
ya and it still doest make the player jump xD
ooh what does the ~ do
@wintry crescent Thanks a lot!
modified code https://paste.ofcode.org/32UKaVQg6dyRzBtnYzvvJZa
Hello, why I cannot access this namespace?
using Mono.Data.Sqlite;
I have installed SQLite
great! no problem!
does your moveforward code use transform.position to set new position? or rigidbody.MovePosition, or rigidbody.velocity
if you're using transform, consider using rigidbody instead
That radius is tiny
ok
Have you imported a plugin or asset that would let you do so?
yes, I have followed this documentation
I have downloaded SQLite database and dragged everything in Plugin folder I have created
yooo fancy linkage
i havent mastered that new markdown yet
but I still cannot access this namespace
nice
regenerate project files
refresh?
its working finally, thank you : ) @buoyant crane and @wintry crescent
Nice
nah, I still cannot use that namespace
whats this ?
its just a link to youtube
but its embed
yes
how
.
oh
no
unfortunate
im trying to get a held item to work but it moves wierdly as I move the camera
it also doesn't make sense
render a camera to a render texture and draw that on a RawImage compoonent in your canvas
hmm
wont that also render whatever is behind the object?
this doesn't sound like something you'd use UI for
im not
ever heard of a culling mask?
canvases are UI
well i know canvases are redered differently
no actually
HandItem.transform.position = transform.position+Camera.main.transform.forward.normalized+(HandItem.HeldPos);
this is what I have so far
why not just use a PositionConstraint?
or
Camera.main.TransformPoint(Vector3.forward * offset)```
