#๐ปโcode-beginner
1 messages ยท Page 448 of 1
yeah im aware
You can compress or make lower res video longer
51.2MB. You won't be able to send it even with Nitro
any tools to compress?
Your dimensions are 3360x2100
Yeah, the main issue is the crazy resolution
if you record with OBS, you can control the video resolution
Yes, google "compress video" and click on the 1st site: https://www.freeconvert.com/video-compressor
thank u!
sorry, I don't understand what saving the value has to do with
Hold on, I'm thinking about the example
public class Animal { }
public class Dog : Animal
{
public int noIdea;
}
In this case, you can create a Animal as a Dog:
Animal animal = new Dog();
This is an Animal now, but you can freely convert back to a Dog and its values will be saved:
if (animal is Dog dog)
// ...
RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up, 1.0f, grNd); anything wrong with this? it isnt working
Maybe, a better example would be with a constructor
public class Dog : Animal
{
public int noIdea;
public Dog(int noIdea)
{
this.noIdea = noIdea;
}
}
I understand downcasting and upcasting for the most part
if (animal is Dog dog)
dog.noIdea // the chosen value
The same goes for enum and object
Everything can be casted to object
And its actual type will be derived from it
so when I assign the object into the object list, which holds certain enum types, the object being assigned is automatically casted to the enum Type if possible?
The object is not implicitly casted to enum
Everything can be explicitly casted to object by either using (YourType)@object or @object as YourType
that would make sense, but for some reason chat gpt (which ik is not 100% correct) says it would be
You are free to choose ChatGPT's answer over mine
lmao no no, thats not what i mean
It's also possible that you're misinterpreting it's answer or it misinterpreting your question.
What i think ChatGPT said is because the Enum.Parse method goes like this: Enum.Parse(Enum Type, string, bool), it takes the Enum Type you put in and uses that
but it returns an object because Enum is a special class or something
To be fair, I don't understand what the question is either. It feels like the conversation is going in meaningless circles.
once i can test this thing out, and if it works, ill ask the question again
no use trying to solve an equation with two unknowns
There is actually a type safe parse method, that I would use if I wanted to parse an enum. Instead the ones that return an object.
https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-8.0#system-enum-parse-1(system-string-system-boolean)
im trying to understand the api but its going over my head
What part of it?
Not sure if coding question, but doesn't seem to belong anywhere else either.
How do I make my bunnies go up/down a little bit, so they don't all overlap exactly?
I think i got it, only cause I already know what its supposed to do
Would it be a bad idea to just disable gravity for monsters? I don't think I will ever use it in my game
Or can you disable gravity for the entire game somehow?
i mean, you can set random height when you set their destination position.
or spawn them at random height, if it's not critical for your gameplay
but then gravity just pulls them down again (I disabled gravity and did it like that)
why gravity will pull them down if it is disabled?
no it works now, just not sure if disabling gravity like that is a good idea
don't see why not tbf, but i'm not that proficient in unity for now.
you can look into charactercontroller i guess, but i never touched that
Could anyone guide me as to what could be happening here? When I create a host after the first time, I'm getting duplicate connection calls of my own client.
I'm using relay to create a host
Why is this not hitting? The Transform y is set to -3.2
When I set it to -3.4 it does hit
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, range, layerMask);
Debug.DrawRay(startPosition, direction * range, Color.red);```
ew my raycast doesn't use startPosition oopsie
Why would it be laggy ?!
because json is slow. it's all string based internally.
you'll also be generating loads of garbage that needs to be cleaned up
Oh nice I dont use json ๐
Also few days ago everyone here told me that what I was doing was Bad and that I should use Json
Can someone help me out here? #โจโvfx-and-particles message
well yes, because it was better than what you were trying to do. You were manually sending the variable names and the data, then also parsing it manually.
dont crosspost #๐โcode-of-conduct
yeah ik I shouldnt, but no one every checks that channel
but yeah ur right
mb
Ok, but if parsing manually is bad and Json is bad , what is the good way of sending data ?
Give me 5 minutes I lunch my computer
it was around here,#archived-code-general message
yeah... thats really bad.
again, you don't want to use strings when serializing real time data for video games.
int Index3 = queuedMessage.IndexOf('X');
int Index4 = queuedMessage.IndexOf('Y');
int Index5 = queuedMessage.IndexOf('Z');
int Index6 = queuedMessage.IndexOf('!');
int Index7 = queuedMessage.IndexOf('R');
int Index8 = queuedMessage.IndexOf("IsAiming");
int Index9 = queuedMessage.IndexOf("IsWalking");
int Index10 = queuedMessage.IndexOf("IsRunning");
int Index11 = queuedMessage.IndexOf("IsHigh");
int Index12 = queuedMessage.IndexOf("IsReloading");
int Index13 = queuedMessage.IndexOf("H?");
int Index14 = queuedMessage.IndexOf("T?");
coordX = queuedMessage.Substring(Index3 + 1, Index4 - Index3 - 1);
coordY = queuedMessage.Substring(Index4 + 1, Index5 - Index4 - 1);
coordZ = queuedMessage.Substring(Index5 + 1, Index6 - Index5 - 1);
rotY = queuedMessage.Substring(Index6 + 1, Index7 - Index6 - 1);
IsAiming = queuedMessage.Substring(Index8+8,1);
IsWalking = queuedMessage.Substring(Index9+9,1);
IsRunning = queuedMessage.Substring(Index10+9,1);
IsHigh = queuedMessage.Substring(Index11+6,1);
IsReloading = queuedMessage.Substring(Index12+11,1);
LivingState = queuedMessage.Substring(Index13+2,1);
CurrentTeam = queuedMessage.Substring(Index14+2,1);
you're causing future you a lot of issues that you're going to need to clean up in the future. this also will not scale at all as player count increases
at the very least just serialize raw binary data. like pointer cast your values into a byte* and memcpy that into your buffer or something
Often you'll just reinterpret the bytes with an offset. No strings involved whatsoever.
ideally you'll want something automated, so you're not doing all of this by hand and creating human error...
you'll generally not want to create any heap garbage at all for network messages
Perlin noise go brrr
I'm sry but I don't really understand what you mean ( because m'y english is not the best) , because with my Websocket I'm obliged to send my messages in the form of a string
you can't send a byte array?
no
you should probably do some research into this if you're dead set on writing your own network code...
or just use one of the pre-exising network libraries like mirror
Your networking api should probably at the very least be able to send it as char arrays, which is basically the same as a byte array
I already try, but I can't find any usefull stuff, I have been working on multiplayer for more than 1 year now and I never find anything usefull, moreover the librarie I'm using doesn't have a lot of documentation
so you see now why literally everyone has told you what you're doing wont work? and that we arent waiting to be proven wrong
I can assure you that using mirror is much simpler than writing your own netcode API
a middle schooler could figure out mirror
Yeah, I'd avoid implementing your own solution if you don't even know what bytes are
I know but I already make a test game using this method, and even with 6 player it was working perfecly fine
if thats how you want to do it, then nobodies going to stop you. I'm just warning you that it's a waste of time for anything remotely serious
Well, if it works good enough for you, then what is the question?
because everyone is telling me that my way of doing is bad (and I'm sure you're right) but I make some test and It seams to work so I'm very confused
try spawning in 40 networked objects all being serialized and deserialized 30 times per second with your string method
your performance will tank. I guarantee it.
It depends on your setup. If you profile properly, you might see that this code eats quite a bit of your frame time.
Which basically leaves less budget for other features in your game.
among other things, your method also doesn't factor in interpolation. so you'll need to be sending packets at the monitor's refresh rate for it to appear smooth
it also uses TCP which uses head of line blocking... which will cause visual jitter and freezing when packet loss occurs as packet transmission will completely halt until all of the missing packets are resent and ACK'd
unfortunately multiplayer isn't as simple as just sending data back and forth.
that why it's a bit laggy some time ๐
I feel so bad now, it's been over 1 year that I've been trying to learn how to make my multiplayer and I can't find anything or anyone to explain to me the right way to do it, and now that I'm almost done everyone's coming to explain to me that everything I've been doing all this time is just crap ...
if you truly want to learn netcode, those links will give you an introduction
you're missing a lot of basic pre-requisites though, like understanding what a byte array is... you need a lot of work in other areas
or just use mirror like a sane person.
For starters, if your game works, don't let anyone discourage you. Your solution might be just good enough for your use case.
That being said, that's the price you pay when you jump into a complex project(like one that requires multiplayer), without proper learning or experience before that.
I'm sure you've been told not to start with a multiplayer project when you first started learning gamedev or unity and you probably ignored these warnings.
you're right, everyone advised me against making a multiplayer by myself, but I know insinde of me that if I'd never made one, I'd never have continued developing video games, so even if my project is far from perfect and the most optimized, it's still allowed me to learn a gigantic amount of information, it's very far from being my first programming project, but it's the one that's really going to allow me to say that I'm into programming.
that's said I'm gonna learn what's a byte array, thx for your help !
like dlich said: if your way works, you can keep doing it that way
my comments are merely suggestions.
your right, but finding out if I can improve my code can only be a good thing.
I actually think I know what you're talking about since I took 1 year of computer science in high school last year, it's just that talking about a subject I'm not an expert in, and in English to boot, doesn't really help me. ๐
imo, if you dont have a concrete plan for the game so far then you should heavily reconsider this whole sunk cost. A concrete plan meaning stuff like how many players you want to support, the actual gameplay planned out, and really just the overall architecture. You're gonna either have to rewrite this system or settle for what you have with the issues that were pointed out above.
I even tried first making a multiplayer game. i rewrote systems so many times, which all was useless because i realized a new feature would require changes. I chose to abandon it to make a singleplayer game and i have around 9 years experience in CS.
yes, the whole string parsing stuff is just a fraction of the issue here.
manually serializing the data will slow production down to a crawl, especially when you start wanting to change things and now you're wondering why your data is coming in corrupted (because of human error ๐ )
It could even be a nice project just for friends to see, but remember that projects have to end eventually. If you aim to upload the game to steam, and it has any lag issues, everyone is refunding it.
that true, that why I want to make the best thing possible, I don't want to scam people
@warm raptor
https://mirror-networking.gitbook.io/docs/manual/guides/synchronization/syncvars
{
[SyncVar]
public int health = 100;
...```
this is how modern netcode frameworks will synchronize variables, for example.
you just tag it with an attribute, and it does everything automatically. synchronizing the state should be as simple as possible during actual game development. you shouldn't be trying to write a netcode framework and a game at the same time. if that makes sense. you should be building your game on top of an already existing netcode platform either created by you or someone else.
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
@lunar lark You've been pointed to #854851968446365696 already on how to ask a question properly. And don't spam bot commands randomly.
I just called the bot once wdym if you helped instead of being such a discord mod nerd
@lunar lark Help with what. You didn't ask any question yet.
So I've made an ingame saving system like the one in hollowknight but Im having trouble with something. My enemies despawn when you enter and that's alright until you want to get out the save point, I want the enemies to respawn after exiting the save point but it doesnt. Sorry for bad englsh.
CLASS1 Enemic:
public void PlayerEnterAltar()
{
Enemic[] enemies = FindObjectsOfType<Enemic>();
foreach (Enemic enemy in enemies)
{
enemy.MortSLS = false;
enemy.IsDead = false;
enemy.CurrentMoveSpeed = enemy.moveSpeed; // Guarda la velocitat actual
enemy.moveSpeed = 0f;
enemy.gameObject.SetActive(false);
}
}
public void PlayerExitAltar ()
{
Debug.Log("Enemics tornen a apareixer");
Enemic[] enemies = FindObjectsOfType<Enemic>();
foreach (Enemic enemy in enemies)
{
Debug.Log("Enemics tornen a apareixer");
enemy.gameObject.SetActive(true);
enemy.MortSLS = false;
enemy.currentHealth = enemy.maxHealth;
enemy.moveSpeed = enemy.CurrentMoveSpeed;
}
}
CLASS 2 Player (where PlayerExitAltar and PlayerEnterAltar are called FILE)
@lunar lark Again. Read the #854851968446365696 on how to ask question properly and post code,
Why all these rules
I understand you, but that's not the way I want to do it, I understand that modern networking may be easier to work with, but my networking litteraly does the same thing, I know that for you I might doing my networking the wrong way, but I didn't want to make a P2P game, I really wanted to work with a server
because its annoying to read unformatted code like that
womp womp
I'm not talking about p2p, but that's okay. you can do it however you like ๐
!mute 731473620949532704 1d I guess try again next time properly instead of wasting people's time.
martiiic was muted.
Oh I might miss understand but what I wanted to Say is that I'm still young and I might not make game my whole life so I think that it's better to learn how to make networking from scratch instead of using things that already exist because it would allow me to use this knowledge other where than juste in Unity game, and I think that this is the kind of things that might help me find a job later
in the real world you build a REST API as your server backend so you can get information from the server.
E.g. for those apps that track stock markets you can then send a GET request getting the latest financial data
alternatively if you absolutely want to learn networking for games without making a game see https://emily-elim04.medium.com/building-real-time-apps-using-websockets-dc137ccdd34b
Thanks, I don't understand it all but it's still quite interesting!
Well, you can both use an existing library and learn how to do it from scratch, by learning how the library works. Especially if it's an open source one. Instead of trying random unoptimal things.
When you have proper understanding of the underlying systems, you can implement your own.
that true, but I make my choice I already buy a vps and I think the way I'm doing will work perfectly fine for the numbers of players their will be in each game ๐
and I will have time to improve, this is only my 2 project with my homemade networking
I don't see why having a server prevents you from using a library
you did not need to buy a vps but wtv
you can test on your own pc or use AWS free tier
you would need a server regardless of whether you use a library or not
but I don't understand what your "librarie" are , Networking librarie aren't just P2P ?
No..?
They're frameworks for networking. Most of them support a wide range of networking styles, including p2p and server based.
It's just that some of the companies that provide them also happen to provide hosting services.
That just shows how little effort you put into researching the topic
or just I start programming a bit more than 2 years ago and was completely loss ?
That's why you research first. To not get lost
And yes, it's a very complex topic, which is why no one recommends you start with it as a beginner
Here's mirror explaining different hosting solutions btw, including a dedicated server:
https://mirror-networking.gitbook.io/docs/hosting/pragmatic-hosting-guide#id-3.-dedicated-servers
You need to emit the signal in the timeline
Oh hrm
Is "CinematicEnd" an inbuilt signal or one you made?
I made it
You need a signal emitter track IIRC in the timeline
And then move it to the end of the timeline
e.g.
I don't know why, instead of helping me, people just keep telling me that I won't make it on my own... Anyway, it doesn't matter, I've always been alone and I've always managed on my own, so with enough hard work, I'll eventually get there. I know they say there's no point in reinventing the wheel, but honestly, maybe what I'm doing is garbage, unoptimized, ugly, and burns your eyes when you look at my code. But I know that doing things by myself is the only thing that motivates me. I know you think I'm stupid and that I should refer to existing libraries, but I know that's not what I enjoy. If we want to have a good game in the end, the most important thing is to have enjoyed the work we've done. I have my own way of working that people often don't like because they think it's not clean enough or professional enough, sure, but unlike others, I see my projects through to the end and refine and rework them until they're good. My network might not be perfect, but at least I can connect players to different games based on the ID they enter, make sure they can move around and others can see the animations they make, ensure the character can shoot and everyone can see the shots, allow players to switch teams and everyone to access the list of different teams, and let players shoot and kill other players while my server detects who killed whom. I've also made 90% of the models myself, including the characters and their animations. I might be a lousy beginner, but at least I have a functional project that's making progress!
As I said, I'm not trying to discourage you or anything. It just seems like you had some misconceptions about networking libraries and networking in general. I was just trying to show you clarify these misunderstandings.
I know, but I'm really sad to see that I've work 1 year to see that everyone is telling that what I've done is trash ๐
Yeah, everyone got there once in their life
imagine you get someone to help you with your game and they see this
sure it works for you but how do you expect them to work with this
Well, what do you expect us to say? Good job on lack of research?
You're asking in a beginner channel. Obviously everyone would try to point out things that you might be doing wrong.
How can I make a system in which objects receive more or less damage depending on the weapon/tool you are holding? is it with Enums???
Hello
You could just pass the damage value of the weapon when dealing damage.
yeah but I dont want an axe to deal the same damage to a tree as a sword for example
I wrote this class in C++
it uses invoked System class from C# to call the binary reader and writer
I am going to do a native call to the methods from my unity C# code
here is the source code
#include <string.h>
#include <msclr\marshal_cppstd.h>
#include "VM.h"
using namespace msclr::interop;
VM::VM(System::IO::BinaryWriter^ writer, System::IO::BinaryReader^ reader)
{
VM::reader = reader;
VM::writer = writer;
};
void VM::Shift_Half_Unsigned_Address_F()
{
System::UInt16 EF = VM::reader->ReadUInt16() * 32;
System::UInt16 EB = VM::reader->ReadUInt16() * 30;
VM::writer->Write(EB);
VM::writer->Write(EF);
};
void VM::Shift_Half_Unsigned_Address_B()
{
System::UInt16 EF = VM::reader->ReadUInt16() / 30;
System::UInt16 EB = VM::reader->ReadUInt16() / 32;
VM::writer->Write(EB);
VM::writer->Write(EF);
};```
my question is how to create the bindings for it?
You could have different types of damage or different modifiers depending on the target. Or have the target have different damage reduction stats against different types of damage. There are many ways to go about it. It depends a lot on your project needs.
Okay, Ill guess Ill go with that, thanks!
any helps?
- I don't see why you need it to be in C++..? You can do the same thing in C#.
- If you really want to do it, you'll need your class compiled into a dll. And imported in C# using PInvoke.
https://learn.microsoft.com/en-us/dotnet/standard/native-interop/pinvoke
yes i am compiling it in dll before using
i just dont know if it will work or not
Well, there's a 100% sure way to tell: try it and see.
๐ฅฒ
when doing a platformer and creating the world with a tilemap what for example if I wanna make some moving platforms but the platform itself may consist of more than one sprite how can I make it so the code can fit to most type of platforms?
dont use a tilemap for stuff like that i guess
so like should I combine tilemaps with stuff like normal sprites u mean?
I'm trying ot unfreeze these caps but they keep falling off due to rigidbody.
Is there a way to freeze the rigidbody until a button is pressed?
like you make your normal level with tilemap, then make moving platforms and stuff without a tilemap
yeah you can freeze it, check the docs for rigidbody
When a button is pressed, not perm freezed
you can change them through code
I'll check rn
if its in the ui there must be a way to do it programatically
oh ok and like when positioning it is there a way to position it without moving it freely and move for example some pixels in a direction everytime I move it in the editor?
like snap to grid type thing? hold ctrl i think or one of them buttons i forgot and it will snap
oh ye
nice thanks
Couldn't find any in the rigidbody doc
For position specifically
is there a way of seeing the trajectory of on which the platform is moving from point A to point B
should that be done with raytracing or something like that?
Should the weapon that my character carries be a ChildObjectof the player?
Still wont work since I'm staring them in arrays
I'll try to figure it out somehow
yeah
huh? what wont work why, what difference does that make
Just gives me an error
well if you want help, you need to show the code and error
and should it have its own component to choose what weapon it is using each time?
you can make like a weapon holder child object, that have a script and then activate/deactivate what weapons you need
Now it doesn't
thanks
Attacking with weapons should be done with triggers? or is it better to do with OverlapCircle
overlapcircle
all i think
thanks a lot
I just looked up what a char array is, and I don't understand how it would be more efficient than a string. In both cases, I would need to retrieve the information I need using indices, and anyway, I don't need to be able to modify the messages I receive or send. Can you explain, because I don't really understand the usefulness of a char array.
Is the whole point sending data over a network to clients?
You don't send stuff as strings then
The reason why JSON is bad is because you bloat up your packets way more than what they need to be and this is horrible when you send inputs and stuff to the server for example. It also requires serialization/deserialization
So if this is some multiplayer game that uses networking, then look into BinaryWriter and BinaryReader
Alternatively make your own packet class that reads/writes from a buffer. It's not a lot of work
I never heard something requiring strings specifically so I doubt that's needed here either
i'm not using JSON, I'm just sending String, but they told me that char array could be a better solution, but I will still look at what you sent me ๐
Actually, char array was a mistake. I was confusing with C++ where a char is 1 byte. In C# a char is 2 bytes, so you can't use them interchangeably. That's why I'd suggest to look at how some of the networking libraries implement it in C#.
Weird that a char is 2 bytes in C#, I've done networking in C using chars. I wonder what that extra byte is used for... can't possibly be a null terminator. I'll have to look at the docs
it's because chars and strings in C# are utf-16
How can I mantain cohesion with my attack component and make sure that I can access the same method "Attack" but it has different effects, for example, I want my enemies to attack with their own attack stat, but I want my player to attack depending on the weapon it has?????????
!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.
So over the years I've learnt some stuff what to do and not to do, as well as the fact you should always keep your code organized.
I have created this script, which I copy and paste into new scripts and edit only the stuff I need, so that everything is organized the same.
What do you think about this and how did I do?
Right, but what is the goal here? Is it a networking solution like I assume it to be?
Sending data to clients etc
There are different patterns depending on how you are communicating, but if it's networking where a game needs to continuously send data, then you should use sockets and a system that sends/retrieves byte arrays basically.
JSON is still valid if the data you send is not continuous and might have a large/dynamic size.
yes I'm making a websocket serveur for my fps
Yeah, then just make a Packet class that creates a byte array and send those instead
ok, but why I need to use a byte array instead of just sending a string like i'm already doing ?
Because you will have a string of varying data which must then be parsed into usable data
It's slow and bloaty
You also have no control over the actual size, so you can't specify single bit data since everything needs enough bits to fit in a whole character, which is a waste of space
It's not just about sending(although it's definitely better to send less data than more without need), but also about processing that data on the sending and receiving ends.
At the moment you have issues with all of these things.
How can I mantain cohesion with my attack component and make sure that I can access the same method "Attack" but it has different effects, for example, I want my enemies to attack with their own attack stat, but I want my player to attack depending on the weapon it has? Basically what I need is something that makes the player or any entity attack but in different ways
It also depends a lot on encoding but regartless you are wasting time converting the string into usable data, which is the worst part of it
Something that is negligible at the start but very noticeable once your game ramps up on the data is sends/retrieves
The socket class and its derived classes also don't allow strings in general, only byte arrays ๐
I first thought it was a class, which you derive from to expand your other class' functionalities, but it does not seem this way.
I understand what you are trying to achive, but I do think it's pretty useless. If I created a script in Unity, and this was its code by default, I would simply remove everything inside of its scope, the same way I do it with Unity's default Start and Update methods on new script creation, along with its descriptions
Can I replace the default script stuff?
But this is merely my opinion, and there is definitely nothing wrong in you using this, as long it speeds up your work. This is something, which is used by you, and you shouldn't be asking others' opinion, because there is nothing to correct, if we're talking about syntax or errors
So my string is converted into something to be send and then this thing is converted back to a string , but a char array won't be converted ?
A char array is a bloated byte array
They are a bunch of numbers
I don't see why you would be using a string here, why are you so fixated on using it?
Another point, using a string will cause culture issues if you use characters of varying culture.
Doesn't speed it up necessarily, but adds a lot of organization imo. I just know where specific methods would be even after a month of not looking into it for example. Or others looking at the code know what to expect where, if they've looked at the mask once
I'm a beginner and to be honest I have no real idea what happens once my code is compiled๐
ok , so let's assume that I'm now using a char array instead of a string, how could I get the information I need from the char array ? because now I'm just parsing my string
So how are you sending data over the newtwork to begin with? Surely you'd have to use a byte array in general?
I don't think sockets accept char arrays since they are still different
I don't think you should have anything regarding char arrays or strings in your code
Please give an example of data currently being send in your game. What is that exactly?
Yes.
C:\Program Files\Unity\Hub\Editor\2021.3.27f1\Editor\Data\Resources\ScriptTemplates
Go to this location and add the suitable code to this file:
81-C# Script-NewBehaviourScript.cs.txt
Note that the location can differ on your device and Unity's version. See more here
Thanks, I found it!
Here's the example they initially presented
#๐ปโcode-beginner message
I have no idea what is happening in that code
Does it generate a string full of key-value pairs?
Is it just sending a lot of booleans?
Additionally,
How to have only one public static "Instance" at a time, while one game object should never have 2 "Instance"s as components
You have to search for "unitysingleton" on the web and copypaste the genericSingletonto your project, which you then derive the suitable classes from
So remove the functionality from your Awake method
so first i create a Websocket in my client
private void InitializeWebSocket()
{
ws = new WebSocket("ws://127.0.0.1:8000/Lobby");
ws.OnMessage += (sender, e) =>
{
message = e.Data;
messageQueue.Enqueue(message);
};
ws.Connect();
}
then I can just make to send the data
ws.Send("my message as a string")
Ohh okay, I thought my singletons were a bit weird
I also feel like you don't need all those comments, because you should definitely know what they mean yourself
Are you making a web game?
In the browser?
Yeah this was created for sharing it, aswell as thinking about why I do stuff rn
no why ?
Will not use the explanation in the document later on
Yes, they are weird if done this way. Remember to not make your class a Singleton if not needed. Only some classes like GameManager and other managers require it
Yep
I have switched to the use of event Action and UnityEvent for cases I would have otherwise used a static class
I assumed WebSockets were browser specific
I would honestly just use a plain Socket class if I were you
Only drawback is risk of dropping packets
Either way the Websocket also allows byte arrays, so you can continue using that
How can I mantain cohesion with my attack component and make sure that I can access the same method "Attack" but it has different effects, for example, I want my enemies to attack with their own attack stat, but I want my player to attack depending on the weapon it has? Basically what I need is something that makes the player or any entity attack but in different ways, please help
I also love creating extensions, the class I derive all my MonoBehaviours from:
It, currently, has 2 partial files, and contains interesting stuff I don't like to reimplement everywhere
So @warm raptor what is the actual data being send in that code now? Is it a bunch of boolean and float values?
Doesn't EntityBehaviour already derive from MonoBehaviour?
By the way, these Actions without the event keyword are not meant to be. I have just noticed and fixed it
Yes, I derive my other classes from EntityBehavior instead of MonoBehaviour
Would you mind sending the whole class over !code? I don't really get why you would define all those Events again (with On)
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Here it's what the client send
GID123X-1,037964Y1,282664Z3,7!84,40001RIsAiming0IsWalking0IsRunning0IsHigh0IsReloading0$
and that was the client receive
(b6cbd7dc2c334d8590ef9b3bc102c557)GID123X-1,037964Y1,282664Z3,7!84,40001RIsAiming0IsWalking0IsRunning0IsHigh0IsReloading0$H?1T?1#
IsAiming0
I assume this indicates that IsAiming is false?
exactly
Here's the thing, you don't have to send over whole keys if what you send is always the same order
So you now send over a string and integer, when a single bit is enough
This is why it becomes messy once your game grows
For example, there's this: https://learn.microsoft.com/en-us/dotnet/api/system.collections.bitarray?view=net-8.0
yes of course, that just that it's easier for now, but I will change this later to like one or 2 character
But at this point there is absolutely no benefit to using a string
Not to mention you are still parsing it for no reason
A byte array has everything in its place
Your floats take 4 bytes instead of how many bytes would be required for the floats currently
FYI a single character is 2 bytes
I've done something like this in the past, but there is a performance cost to defining Unity event methods, even if they are empty. If many of your scripts inherit this and don't use all of the events, it's sucking performance out of your game.
So your floats in this example is 4.5 times as big
Absolute waste of space and it will slow down everything if you do it everywhere
I'm so sorry but I don't understand why you speak of float because my whole message is a string no ?
You're passing float values as a string
Yeah, that's something for me to think about
A float is normally 4 bytes, and now you convert it to a string and make every single character 2 bytes
A float doesn't span a list of characters, it's numbers. But your code doesn't know that
So, a byte array just stores the 4 bytes that defines your float, and you send that over
Then the receiving client parses the bytes back to a float using BitConverter.ToSingle
Are you using this library?
https://github.com/sta/websocket-sharp/tree/master
Because the dotnet WebSocket doesn't have a Send method.
yes it's this one
Even they do conversion under the hood https://github.com/sta/websocket-sharp/blob/master/websocket-sharp/WebSocket.cs#L3461
You're just adding extra work for the same result
Ok, well then you can look at their source code:
- They have a send method that takes a byte array.
- The method that takes a string, actually converts it to a byte array for you.
You're just doing double work with using a string
Is it better to attack with triggers if the hitbox is going to vary or with OverlapCircle??
ok I'm so sorry and I might be dumb, but I saw that a bite array is some sort of a list, but if I receive this list I will still have to tell to my script where is the information for the rotation, location ... like what I'm I doing with my parsing in my script ?!
What do you mean where it is? Your data will always be the same
Assuming your byte array first writes a float and then a boolean, the float starts at index 0 and the boolean at index 4
You can use a binary reader/writer like Fused suggested, to parse the byte array.
I'm quite confuse (and my bad english doesn't help at all ๐ฅฒ ) if I send a Byte array will I just have to send the same things as my current string but in a byte array form ?
Yes, everything is bytes under the hood
This might be confusing, but this is a packet class I wrote and maintained for a while. Here's purely the parts for writing/reading a float https://gdl.space/lowiceriqu.cs
Whole point is that is uses BitConverter for reading and writing bytes from and to the correct type
The code around it ensures it's written/read correctly by getting the correct spot from the array, and some other validation stuff (like making sure the length doesn't exceed 255 since that's the max number a byte allows)
for (int i = 0; i < allowedApps.Length; i++)
{spawnedApps[i].GetComponentInChildren<SystemUIButton>().onButtonClicked.AddListener(delegate
{
ComputerManager.instance.OpenApp(allowedApps[i]);
});
}
im trying to add listener to an Unity Event with parameters... but it just gives me "IndexOutOfRangeException" on allowedApps[i]?
spawnedApps is probably not as big as allowedApps then
it is
Debug it. Don't assume.
Then debug your code and see where it fails. This is the only assumption that can be made from this code
brother i see it in the inspector
Brother, what you're seeing in the inspector might be a totally different thing at all.
That's still assuming. Actually validate it by logging the length of spawnedApps and allowedApps before this code runs
I barely understand something to your script ๐ญ
If you get an IndexOutOfRangeException, it's either your eyes or Unity's visuals to doubt
The main point is that you can use BitConverter to turn your float into a byte array and back. Most of the code just puts it inside the main byte array that is send, and also reads from this (which is what the receiving end does)
I suggest you try making something similar
its the same :3
It's kind of hard to make a proper byte array of data without one, but the BitReader thing also works
It seems like you miss a very basic and important thing: how data in computers is stored. You should learn what bytes are.
Then the exception is not in this part of the code. Send all your code and the full error
my brain gona explode ๐ฐ
I also suggest your improve your code by separating it into chunks. Right now a single line can throw multiple exceptions and it will be unclear what went wrong to begin with
Welcome to programming
Honestly if you're a beginner I'm not sure if you should be doing this to begin with
in english a Bytes is 8bit ? because im not sure of the translation
Isn't it easier to make a very simple console application that sends some data around first?
I'm 99% bytes are bytes in every langauge, but yes, it's 8 bits.
nope in french bytes are "octets" xD
I guess wikipedia is lying then
https://fr.wikipedia.org/wiki/Byte
I think it's not an issue of translation, but of learning some programming basics
oh yes my bad
in finland we call bytes syllables, no idea why
probably because 2 bytes is a word
Also, I'd say that English is very important for programmers. It is not my native language either, but I read docs and have my environment configured to be in English.
I might have understand you want me to have a message where my client could modify a part of the message, then send the exact same message that has been modified and then let the serveur modify the message again and again ?
You want to modify the data and send it back?
You can still do that with byte arrays
However, you should understand that byte arrays assume that the data your send is always in order and of the same size. I assume your editing retains the order and types
It's weird to do this though
not necessarily, i thought that's what you wanted me to do
It's expected you send bytes over under a specific key, and depending on this key the client knows what the data in the byte array represends
For example, key player position indicates the byte array might be three floats representing a Vector3
Oh I "THINK" i've understand !!!
but that mean that I have to send way more message to the server
Should my attack component be in th echild object of th e player or in the player?????????
because now I'm sending one huge message for all the different values
oh no I know, I have to put a key for each part of the message, so I wont need the "separation letters" anymore ?!
Whatever works for your architecture
There is no definite answer
solution i found?:
Youโre almost thereโฆ the above is likely perfect EXCEPT that C# does โvariable captureโ instead of value capture.
This means that your listeners will ALL be created and use the final value of i, not an ever-increasing 0, 1, 2, 3 etc which is what you want.
what 
Right
that is absolutely correct;
make a local variable
int ix = i;
and pass that to your method
I missed the part where you made a delegate
Consider just making a method that opens the app and pass the app by reference instead of using an index into the array
That way you would not have this issue to begin with
Also, proper debugging would reveal that a long time ago
That would imply you didn't actually debug log in the correct places.
Or the correct variables
I never gotten this error but it decided to give it to me now
It didn't show up as an error when I added it ages ao
It's because you recently added a new using directive to your class
https://unity.huh.how/compiler-errors/cs0104
Probably the wrong Random. Hover over it and see the full type name.
Class system
Probably "System.Random".
And the one you want to use is?
The other one.
"the other one"?๐
UnityEngine.Random, right?
https://docs.unity3d.com/ScriptReference/Random.html
again, this is due to you adding the System using directive. there are two Random classes you currently have access to and the compiler needs you to specify which one you want to use https://unity.huh.how/compiler-errors/cs0104
their is something that I still don't understand , If I'm sending my data like that
ws.send("data");
and that by doing this way it's sending a string, how can I make to send a char array ? something like that ?
char Data[] = "My data";
ws.send(Data);
because I found that apparently the socket I use can't directly send char array and instead I should send Bytes array
Did you miss my message about chars being a mistake? You don't need to send char arrays.
We've been saying several times that what you need is a byte array.
Not a chat array.
oh sry my bad
Indeed, just look into setting up a byte array and then reading from that again
string has a getbytes method and the c# Encoding class will convert back to string
As for the keys, if you really want to use them, you should probably replace them with an int or enum.
In this case that would just be the same as what they're already doing.
I'm not getting into this ridiculous discussion, just answering the last post
Anyways, the main issue is all that string parsing you're doing.
Which is why a byte array would be better. It would be much faster with a binary reader/write instead of parsing the strings
Yes I know ๐ even just by looking at it i knew it wasn't the best way
And finding substrings.
Which is exactly what everyone was talking about from the very start.
ok so if I use a byte array, I will receive a sequence of numbers in a list and then I would just have to tell to my script for exemple that from the [0] to the [10] it's where it's written the X coordinate ?
*you will receive a sequence of bytes in an array
It's not the same as a sequence of numbers in a list.
But yes, though you'll use a binary reader instead of "telling your script".
You would be telling your script the value when you have it after retrieving it with a binary reader.
so I would have to do something like that ?
x_coordinate = data.Substring(0, 10);
No. You don't use strings. Or substrings. Period.
The whole conversation so far was that you don't use strings.
my bad ๐
Anyways, I'm off to sleep. Good luck.
okay, thx a lot for you're help , have a good night !
can anyone help me with my shader graph?
in a coding channel?
no not here, i just joined this discord and wasnt sure if i even posted my question in the right channel, and because i saw this one was more active, i thought i might just ask, whats the worst they can say?
so if I receive a bytes array like that :
[88, 49, 50, 89, 51, 90, 50]
wich reprensent this message :
"X12Y3Z2"
how can i get the value for the X Y and Z coordinate ?
why are you using a string format if you are sending a byte array?
i mean, just parse the string
or marshal it to/from a struct with floats/ints in the first place
why are you converting the string to chars then sending those as bytes?
you should look into how to serialize your data properly instead of making seemingly random guesses at how it works
Idk everyone told me to send my data as a bytes array
i am aware of that, but you are still doing exactly what you were also told not to and still thinking of your data as strings
learn how to serialize your data and encode it as binary, then you just deserialize it into the data you need. you don't need this middleman string manipulation
why you are now talking about binary, I'm so lost ๐ญ
iirc you were told a lot about basic issues when approaching netcode naively without any foundational knowledge of how networking works. Maybe you would benefit from looking at a foundational intro into networking. It doesn't even have to be game related, but you should at least understand how bits go from one app/pc to another app/pc --> maybe start by looking at https://en.wikipedia.org/wiki/OSI_model and https://en.wikipedia.org/wiki/Marshalling_(computer_science)
The Open Systems Interconnection (OSI) model is a reference model from the International Organization for Standardization (ISO) that "provides a common basis for the coordination of standards development for the purpose of systems interconnection." In the OSI reference model, the communications between systems are split into seven different abst...
In computer science, marshalling or marshaling (US spelling) is the process of transforming the memory representation of an object into a data format suitable for storage or transmission, especially between different runtimes. It is typically used when data must be moved between different parts of a computer program or from one program to anothe...
help psl
did you do what you were instructed in #๐ปโunity-talk and install the InputSystem package?
im not sure how
i dont have access to packet manager in safe mode
then next time, instead of completely ignoring that suggestion ask how

soo.. if u dont open it in safe-mode it crashes u say?
he directed me here
"if there are more" was in reference to "if there are more questions after installing the input system package"
ill go back to unity talk then
jsut fucking install the package if you haven't already
nobody is saying to go back to that channel to continue ignoring the suggestion. we are saying to actually follow the suggestion you were provided before anything else
exit safe mode? you were literally told to do that when you went back to unity-talk too
to exit safe mode i need to eliminate the error, or unity crashes
to eliminate the error i need to exit safe mode
can you see why I am lost here now?
if its crashing.. you'll probably need to clean it up enough in safe-mode that it doesn't crash
//comment out broken code.. or get rid of hte script until u fix it
a single error about an incorrect namespace would not cause unity to crash. in what way is it actually crashing
^ yea, im suspicious as well
It closes immedieately after opening and the bug report window opens
Ive fixed the error in the script and its loading now, Ill let you know how it goes
then i imagine something else is wrong with your project as well
perhaps
and, here we are again, #๐ปโunity-talk message
it could be because of the missing namespace, or as boxfriend said, something else is wrong
forget could be. look at the damn logs and know
wrong logs, you are not even in the correct folder
again, that error would not have caused a crash in the editor. something else is wrong with the project. installing the webgl module to the project had literally nothing at all to do with your error. so if it was crashing prior to seeing the error as a result of the attempt to add the module then your error (while easily solveable) is not related to the crashing issue
assuming the error caused it is like breaking your arm then on your way to the doctor you stub your toe and tell the doctor that stubbing your toe is causing your arm pain
well i certainly won't be downloading the file to find out
it might be if you posted it using a paste site
alright sorry
simple one for you
isPoisonBubble is set to true and yet it went down the false route
well first #๐โanimation
and second, are you certain it wasn't already in that state by the time it was set to true?
all paste sites say i have too many characters, is there a solution?
read the logs yourself or only share the relevant part(s)
that does not seem relevant to the crash
I'm guessing that is the log from the copied project not the original
clear the logs, then cause the crash again and read the logs again. also i thought you said you'd fixed that error? if you had, obviously any logs related to the error would be old and no longer relevant
oops sry
!logs
yh thanks
yo guys why is that last break point not being reached?
Either because the video isn't long enough or because an exception is being thrown
youre right im getting a NRE
yeah so one of the memories in the list is null probably, or an NRE in the event listener
May need some help trying to get my projectile to instantiate in a horizontal start. It seems to spawn in standing position even though it's zeroed out in the prefab
if (Input.GetButtonDown("Fire1"))
{
GameObject Arrow = Instantiate(projectile, arrowSpawnPoint.transform.position, arrowSpawnPoint.transform.rotation);
Arrow.GetComponent<Rigidbody>().AddForce(transform.forward * launchVelocity, ForceMode.Force);
}
You're using arrowSpawnPoint.transform.rotation as the rotation
so presumably whatever arrowSpawnPoint is, it's oriented improperly.
or perhaps the mesh of your prefab is oriented improperly
the fix is to fix whichever of those is wrong
This is my arrow spawn point
Generally it's shooting_origin but I was trying something out
right so it's going to spawn the thing with that orientation.
If you look at your prefab, you should make sure the "forward" is actually correct on it
Ah to be honest, it's not actually a prefab. Let me check that out
BTW make sure your tool handle rotation is in Local mode
not global
also you should proably use a real prefab ๐
i'm confused
where's the prefab
isn't this your "shooting arm"?
Where's the projectile itself?
isn't this the same thing from here?
Ah, second image of my original post
yeah you can see
the blue arrow is pointing sideways
the arrow is not oriented properly
blue arrow = forward direction
yellow is "up"
red is "right"
orient your projectile prefab accordingly
Can I do this through prefab mode?
of course
So the aim is to get it to face the z-axis from the prefab or the compass in the topright?
you want the business end of the projectile aligned with the blue arrow here
when the root object of the prefab is selected
aligning it with the compass in the top right just means that your prefab root is also zeroed out, which is good practice as well
the simplest way to fix this is to move the collider and the renderer to a child object
rotate that child as needed
So I double up on the renderer and collider? Because the object disapears if I remove it from the prefab
why would you remove it from the prefab?
You want me to move those two into the child I made?
instead of:
Arrow (Projectile script, Renderer, MeshFilter, COllider, Rigidbody)
Do this:
Arrow (Projectile Script, Rigidbody)
Visuals (Renderer, MeshFilter, Collider)```
yes
well it's not an object after that happens
i have no idea what that sentence means
Here it is in the child
you didn't move the mesh filter
why is this only showing out of bounds when the object is already half way out of the camera view Vector2 viewPos = cam.WorldToViewportPoint(transform.position); float verticalInput = Input.GetAxis("Vertical"); transform.Translate(Vector3.up * verticalInput * _speed * Time.deltaTime); if (viewPos.y >= 0f && viewPos.y <= 1) { Debug.Log("In bounds"); } else { Debug.Log("out bounds"); }
what are you expecting it to do?
presumably the center of object is where transform.position is
so it will happen when the center leaves the screen
when the top of the object goes out of bounds it prints out of bounds
but like you said it triggers in the center
so how can I get the top of it
Two approaches I can think of:
- Make empty child objects at the extremities (very top/very bottom) of the object, and check the positions of those for your bounds check
- Put colliders at the edge of the screen and use physics to detect it.
thank you
Or:
- Mathematically calculate where the top/bottom of your object are and use those calculated positions in the check
this is probably the best option for me
how should I handle yamldata when importing through unitywebhandler? having some issues going from the uri to yaml data to give to yamldotnet
Not having a good time with this one
what problem are you having
- Main Object (0,0,0)
- Graphics
its pretty simple.. adjust ur child objects the way u want.. ur main root object can stay str8.. can stay scaled to 1:1:1
also using negative scale is not usually the best idea
Well the object looks much fatter now and rotating just the child doesn't make it alligned
Il delete the object and just remake it, it's only a cylinder prefab
make sure ur lookin at Local Rotations
your previous image looks correct.. (just needs scaled down).. u can see the gizmo in the top right.. showing the Z axis is facing to the left.. so ur capsule is lined up w/ that
we don't care which way the child is pointingt
the root of the prefab is what matters
Ah so that is setup correctly then
ya, bro. the child can point anyway u want it too..
the root is what matters..
(what would hold a rigidbody) (what would have its direction rotated/modified) (what would be used for orientation)
- Root
- Graphics
thats why we use this type of setup
So this is a code issue then?
whats wrong w/ it?
if u want it facing the other direction.. u just use the rotation part of the Instantiation method to orient it how u want
still spawns upright
show it after it spawns
instead of hte prefab view
and yes, its probably code related if its spawning w/ a rotation
spawns facing up
is it hitting anything that would cause it to rotate weirdly?
try spawning it by itself..
// Instantiate a prefab at the position and rotation of the current transform
Instantiate(prefab, transform.position, transform.rotation);```
```cs
// Instantiate a prefab at the position of the current transform with no rotation
Instantiate(prefab, transform.position, Quaternion.identity);```
when u drag the prefab into the scene hiearchy manually.. (that would be exactly how it looks if u spawn it in using code w/o rotation)
yeah make sure it's not colliding with anything as it spawns
il respond in 30 mins, just had to hop out
and when u share screenshots.. select the objects in question.. and make sure not to clip anything out.. (the more we can see the better chance u have at receiving help)..
is pathway down ?
is this a code question?
ooops sorry
I really like using Scriptable Objects for data, I like being able to edit their values right in the inspector. however, they can't be serialized, which makes me wonder if there's a good alternative out there besides using them? right now my workflow is to use a scriptable object to represent one instance of a part of the game - for example, a scriptable object per monster I want to be able to create.
they can't be serialized
When you say this I guess you specifically mean "with JsonUtility"
This is what happens and this is the code I have
if (Input.GetButtonDown("Fire1"))
{
GameObject Arrow = Instantiate(projectile, transform.position, transform.rotation);
Arrow.GetComponent<Rigidbody>().AddForce(transform.forward * launchVelocity, ForceMode.Force);
}
I don't actually know what that is, sorry.
I'm not using any 3rd party tools, this is Unity just getting mad when I add System.Serializable to anything inheriting from ScriptableObject
I am very happy to be proven wrong, if you want I can copy-paste my save and load flow
oh wow! this looks like it might solve my problem!
thank you for the thousandth time Praetor Blue, I feel like every time I come here you're always here to save my butt
scriptable obejcts are serialized by unity, what do you mean they can't be serialized?
I am using binaryformatter which doesn't work with scriptable object, but looking at the docs for JsonUtility it looks like switching to the new flow might work for me
you should stop using binary formatter immediately anyway.
did you not see the big yellow warning in the docs?
have a look at Json.NET which unity includes by default
taking a look!
With it you can mark up exactly which fields/properties you want to serialize.
thank you! ๐
It may be because you give it a rotation using transform.direction
you may also find that you don't need ScriptableObjects at all to serialize your data to disk.
I like using them because I like being able to drag and drop them around and edit their values right in unity
yes, but you do not have to serialize the SO directly, you can just use it for that access and implement the serialization with plain c# objects
which is much simpler because with SOs you need to .Populate an existing object which is often not supported by serialization libraries (though Json.NET supports it)
with a plain struct or class you can just have the serializer create a new instance without any unity object lifecylce issues
I'm not sure if Json.NET necessarily ends up in all default projects. Add com.unity.nuget.newtonsoft-json by name in package manager if you don't have it.
Well it shoots forward when it there is no angle from the character. It's only when you aim away from the centre of the z-axis
Ignore that, it's always facing up no matter the direction
you may also need custom serializers for some unity types. Something like this https://openupm.com/packages/jillejr.newtonsoft.json-for-unity.converters/
Pretty sure Unity has converters for most of the common types.
The only thing I can think of is the projectile only heads in the direction the camera is facing
i think that's the same one, actually. the person who made it also did the newtonsoft package that unity forked
because parsing strings is slow. that's a fact.
reinterpreting 4 bytes as an integer, or 2 bytes as a short, etc is lightning fast on the CPU.
you just deserialize the bytes into variables the same order you serialized them. there's no real parsing needed.
as other people said: it's byte, not char. bytes are literally just raw memory on a computer.
public void Serialize() {
write(variable1); // int32
write(variable2); // short16
}
public void Deserialize() {
variable1 = readInt(myByteArray);
variable2 = readShort(myByteArray);
}
we don't need to parse anything, because we already know that an integer will always be 4 bytes, a short will always be 2 bytes, etc. we can just increment the position after every read/write.
Yeah but you're still giving it a direction. Look at the direction of the main player, the one that shoots the bullets and set all the 3 values to 0, you might find that now your player is sideway
so I have to send one message for each variable ?!
no
you load them all into a byte array
the byte array is your message
that was very incomplete psuedocode
I must be dumb but I still dont understand how it work
hey guys im having problems with point light on unity hdrp
https://www.reddit.com/r/Unity3D/comments/1ejcz4f/help_with_lighting_hdrp/
if anyone could help id be grateful
@warm raptorhttps://learn.microsoft.com/en-us/dotnet/api/system.io.binarywriter?view=net-8.0
look at the example. see how familiar that looks to my example?
I changed the code now, instead of it facing up it now faces forward no matter the direction i'm facing. Meaning it faces forward on a global scale (Always facing towards the X-Axis)
Ok
How can I make a system in which I drag a slotยดs item image and drop it in other slot and that second slot gains the first slot information??
Iยดm using these interfaces for now but I donยดt really know how to detect that the place I am dropping the image is a slot for example
So i made this simple dash but how do i make it that i only can dash once and not again until i touch the ground again
@warm raptor
the whole underlying basis is that memory is stored in bytes. you understand?
every integer (32 bits) will always be 4 bytes in computer memory.
every float (32 bits) will always be 4 bytes in computer memory.
every short (16 bits) will always be 2 bytes in computer memory.
It's just very easy to convert the values to bytes.
bytes are how data gets sent over the internet.
when you send a string over your websocket, it breaks it down into a byte array before truly sending it.
I understand that it's stored in bytes but i don't understand how it work how can integer always be in 32bits , because it would say that you can't have an integer bigger than sommething like 200 000 000 ?!
the max is about 2 billion for a signed int yes.
this is basic information that you should absolutely already know before attempting to do any sort of networking
but that dumb, because their are so many case where we need to go above 2 billion ?!
well there are other data types you could use for that. which is, again, fundamental information you should have before attempting to do what you are attempting to do
I love to see that I know nothing on how the script is interpreted by the computer ๐ญ
also I just see that the web socket I use send the data in binairy, should I go to
e.RawData
instead of
e.Data
?
64 bit unsigned (ulong) integer max size is
18,446,744,073,709,551,615
which you'll probably never need to use a number that big ๐
how can I get a component from the object I am dropping my slot image on??
I want to add the slotData of the Slot image into another slot in which I drop this image
clicker games would like to introduce themselves.
I think eventData.pointerDrag.GetComponent<...>
let me try
physics enter the chat* ๐
that would be the dragged object, not the object it is dropped on, no?
physics engines use 32 bit computations. at least physx does.
i don't remember
could be
I always have to re-figure out how to do drag/drop
could just raycastall from the event system at the position the object is dropped
My idea is to drop the slot image onto another slot which receives the first slot data and adds it to it
but their are numbers that are insanly big in physics ?!
how could I do that?
start by googling it
with PhysicsRayCaster2D?
definitely not physics
"from the event system"
!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.
NRE means SlotData is null here
or you don't have an Event System in your scene
I do have it
time to print out the individual objects (or set a breakpoint and look at them) to find out which is null
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ParalaxScript : MonoBehaviour
{
private float length, startpos;
public GameObject cam;
public float parralax;
// Start is called before the first frame update
void Start()
{
startpos = transform.position.x;
length = GetComponent<SpriteRenderer>().bounds.size.x;
}
// Update is called once per frame
void FixedUpdate()
{
float temp = (cam.transform.position.x * (1 - parralax));
float dist = (cam.transform.position.x * parralax);
transform.position = new Vector3 (startpos + dist, transform.position.y, transform.position.z)*Time.deltaTime;
if (temp < startpos + length)
{
startpos += length*2;
}
else if (temp > startpos - length) {
startpos -= length*2;
}
}
}```
I tried to make paralax effect but somehow it always out of bound and always moving at same speed
why my camera position different than my background position? even though it placed perfectly on the same place
why are you multiplying a position by deltaTime
some tutorial said to make it updating at same rate on any device. So I tried it to debug my problem beforehand. Yeah didn't change anything
it makes absolutely no sense to multiply a position by deltaTime
so, im having a problem that i have never had before in my years using unity, i THINK it might be a memory leak, but honestly i have no idea and ive never dealt with a memory leak before, but when i start up my project which btw is a practically empty project right now, it runs great, 200fps in play mode, but then as soon as i change something in the scene for example changing a value of my move script, add/remove any script, add/remove a mesh, ANYTHING, my frames instantly are reduced to a constant 50/60fps when already in playmode or when clicking play the next time until i reload the scene or restart unity. No fucking clue whats going on here any help is appreciated
wait I'll change it if it was the culprit I'm going to cry alone
nope still broken
Anyone pls
is this the palce to talk about camera
this place is called "code-beginner"
Yea but can i talk about camera is there a way to make it stay one Z position at all times
Sure, when you move the camera's position, set its z position to what you want.
okay thanks
I'm trying to write code to make it so that when 2 objects collide, they merge into 1. But instead both disappear because the code is running at the same time on both objects.
Not sure how to avoid that.
private void OnTriggerEnter2D(Collider2D other)
{
if (other.GetComponent<ItemPickUp>() != null && quantityToPickup < ItemData.MaxStackSize) //if it's another item and this current item has capacity to merge
{
var itemOnFloor = other.GetComponent<ItemPickUp>();
if (itemOnFloor.ItemData == ItemData) //if both items are the same
{
int availableToMerge = ItemData.MaxStackSize - quantityToPickup; //finds amount that it can add to stack
if (itemOnFloor.quantityToPickup < availableToMerge)
{
itemOnFloor.quantityToPickup = 0;
quantityToPickup += itemOnFloor.quantityToPickup;
quantityText.text = quantityToPickup.ToString();
}
else if (itemOnFloor.quantityToPickup >= availableToMerge)
{
itemOnFloor.quantityToPickup -= availableToMerge;
quantityToPickup += availableToMerge;
itemOnFloor.quantityText.text = quantityToPickup.ToString();
quantityText.text = quantityToPickup.ToString();
}
if (itemOnFloor.quantityToPickup == 0) //if the other item is full consumed then destroy it
{
Destroy(itemOnFloor.gameObject);
}
}
}
}
jsut make sure it only runs on one of them
Yeah... but how? ๐
a cheeky way is something like this:
if (gameObject.GetInstanceID() > other.gameObject.GetInstanceID()) return;```
Works, thanks a lot!
๐ 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.
Surround code with three backquotes. Not quotation marks.
oh ok
but also - for a whoile file like that, just use a paste site
oh ok
how do you see what people added to the project in unity version control
https://hatebin.com/qlqutmanpg
can anyone explain the code in the update function
im really confused
it sets the sprites parent to the scripts gameobject.. tracks it.. and uses velocity to squash and stretch the local transform of the child object (the sprite)
void Movement()
{
float speedX = Input.GetAxisRaw("Horizontal");
float activeSpeed;
if (Input.GetKey(runKey))
{
activeSpeed = runSpeed;
}
else
{
activeSpeed = walkSpeed;
}
rb.velocity = new Vector2(speedX * activeSpeed, rb.velocity.y);
}
Hello guys. I am making a 2D game with Rigidbody movement. How i can make my Player move with rb.AddForce without being slippery?
Wdym by "slippery"? You mean having momentum?
Objects have momentum, that's how physics works
If you want no momentum at all you can just set velocity back down to zero whenever you want.
otherwise, you can control how fast to slow down by applying braking forces
how i can add breaking forces
With AddForce
But like to what direction
and it's braking* not breaking
the opposite direction that you're moving in of course
I don't know what you're trying to say, but I'm explaining how to do what you want to do
ok bro ty
how can i turn a gameobject into a prefab without breaking the Variables?
my prefab looks like this
prefabs can not refer to any objects in a scene
well the component prefab
so if you have any references to scene objects, they won't persist in the prefab
alright, so for example the S is for another script if i turn the gameobject with the S script into a prefab can i then bind it and will it then work?
depends what you mean by "work"
depending on what that S is, it's not going to actually do anything
since it's a prefab and not in the scene
yeah but once it is in the scene
prefabs are things that live in your project folder
that would be a different object than the prefab
it would be an instantiated copy of the prefab
your prefab cannot refer to objects in the scene.
regardless of if they are copies of a prefab or not
soo what can i do to make the enemy into a prefab with the same components?
it has the same components
what you need to fix is how you get references to those things
you can't use inspector drag and drop for this
i fixed the S, ST, and SP since they are trying to access a script but the PlayerBody is a gameobject and even if i still turn it into a prefab it wont work
I feel like you're missing the point of what I'm trying to say
no i think im not explaining correctly
it works i made it so they work now
You either use something like the singleton pattern or have the script that spawns these things pass the reference they need to them after spawning it
i just need the PlayerBody To be set
interesting
There's a difference between "you managed to get something dragged into the inspector" and "your game works as you intend"
you'll see
again i dont think i explained myself correctly but that is irelevant now
whats simpler?
hopefully they are
SOmething lIke "shop" or "stats" doesn't seem very singleton
those are scripts
obviously
yeah
singleton means "there's exactly one of them in the world"
the playergoto is now the issue im facing
oh
then it should work? the playergoto is in the world
and there's some code pattern to take advantage of that for easy references
I think you're expecting some magic to happen. You will need to write some code and change some existing code to use the Singleton pattern.
poop
i mean i can probably make it so the ememy goes to the player differently
like instead of going to a specific gameobject it checks for a gameobject with a specific tag in it then it goes it?
This is a very solved problem with very well known solutions
yes, that's one of the solutions
woudlnt i be using raycasts for that then?
Huh? Raycasts?
idk last time i watched a tut on raycasts it said smth about info of a gameobjec
ima read the link first
You're conflating and confusing things
you can get a reference from a raycast sure
if you happen to have been making a raycast in some known direction
but it doesn't sound like you're doing that.
That would be for like some kind of searching behavior
I have successfully gotten my yaml to parse, now I need to figure out how to make it accessible to other scripts, how can I go about making this var visible to a different script?
the same way you do with any variable, either make it public or give it a property with a public get and private set
but that seems to be a local variable, it needs to be declared outside a method
here's the context of the line, and yeah adding public in front of it just breaks everything lol
also been a long day of trying to get this to work hahaha, not entirely understanding what you mean by declaring outside a method
just like at the top of the script?
well you should really start with c# basics then, if you dont understand what outside a method is
honestly just never heard someone use the term method before with this stuff, but fair
Then you haven't learned C# at all. Because it's one of the most used words in it's context.
It being a beginner channel doesn't mean that we're gonna make C# basics lectures here for anyone lazy enough not to learn them on their own.
And spoon feeding such people would just make them get used to getting easy answers without putting any effort.
hey i was wondering if i could get some help with some code?
i'll just post it here. any help would be greatly appreciated.
i just need a simple walk script where i can move around with wasd, jump with the space bar and look around with my mouse.
lastly, i need to make a separate cube that when the player touches, they get sent back to the starting point (they die essentially.) thank you in advance.
i had a problem with this where it grabs the prefab's transform instead of my object in the scene
how can i grab the in scene objects transform here?
been tinkering and bugtesting this all day ๐
Where should we be looking? Are you talking about the commented out code?
no
the line above debug log
tile newtile = (tile)boardmanager etc
thank you
right above the commented code
If you're absolutely sure it returns the prefab transform, then the issue is in the GetTile method. You'll need to debug that.
You can pass an object as a second parameter to the debug log. This would highlight the object when you select the log message. Can be useful for confirming what it actually references.
THANK YOU
very helpful info for debug
appreciate the help
i have no clue what ive done
and now there is kind of a saving mechanic in my game
i made the enemies into prefabs then made it so instead of the enemy going to a specific gameobject it searches for a gameobject with a specific tag then goes to it and now my money is being saved
i mean i aint complaining
i mean i know how to fix it
it highlights nothing!
does that mean its the prefab reference not the object in my scene
i would assume so?
im in the game display i dont know if maybe my settings arent right to see this outline
It would highlight a prefab too. Do you have the assets tab open?
no clue what that means, but hey, if it works it works..
generally: prefabs can't access things in teh scene.. and scenes cant access whats within a prefab..
until after u instantiate it..
then:
- its common to either search for the components in teh scene u need..
- assign them via the script that did the instantiating..
- or simply u can just add the scripts to the prefab
but when i google it says i just need to instantiate it first ๐
so i feel likke i did that
any intuition here?
i have no clue but i think its that i made the gameobject that has money into a prefab? i have no clue myself?
i mean its neat
i know how to fix it
Hmmm..? Oh GetTile is not your own custom method?
eh il make it so once the game starts it makes it so the money = 0
https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0176?f1url=%3FappId%3Droslyn%26k%3Dk(CS0176)
I'm beginning to think the tutorial I'm following is maybe not very good? This feels very analogous to something Boxfriend told me last time I was on here.
Yeah what the hell.
That's why you should be sharing the whole !code correctly. I have no way to tell what objects are of what types there.
๐ 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.
nvm i found the issue that also quite breaks the code
it only works half the time
aha myy bad i wasnt trying to overcomplicate things but
my money is stored on a gameobiect but now instead of storing it on a gameobject it stores in it the prefab
and it seems like its updating but it isnt
what do you mean !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.
the whole file?
I'd assume that one of the references before GetTile is actually a prefab, but it's hard to say without debugging properly and seeing the whole code.
mhm ok
See the bot message? Read it.
sryy ๐ bad discord ettiquette
Yeah, snippets very rarely are enough to go off of. Things like that are your friend since you likely have tons of interlinked code making reference to one another.
I need to get more into that habit myself too so don't feel too bad.
still use the gameobject like u did before.. if ur prefab needs a reference to it and its in teh scene
store the reference on the thing thats spawning the prefab.. then u could just set it..
like ur example had S for spawner..
public Spawner spawnerReference; // <-- on the script that spawns the prefab
then: when u instantiate it..
ChildFollow newChildFollow = instantiate(childfollowprefab);
newChildFollow.S = spawnerReference;``` tha'd be the easiest way i can think of
yeah i need to set the variables to the stuff on scren
but you could also use a singleton.. and have 1 gamemanager type class that holds all the important references from the get go..
you need something important... just access that..
like i need it to be refrenced
i tried using singletons but im having a hard time with them
https://gdl.space/nixexasadi.cs movingobject script
https://gdl.space/fovihiyiyo.cs enemy script subclass of movingobject - this is the movingobject im testing
https://gdl.space/oseqevewuy.cs game manager, it moves pieces around and manages the current state of the game
https://gdl.space/fozowecopu.cs board manager, sets up the board and places pieces at the start of the scene
dont expect u to go through a bunch of work just posting in case u wanted to help xp
not all my files but everyything associated with the problem im sure
some comments may be outdated
they're pretty simple once you start using them. ```cs
public class MyScript : MonoBehaviour
{
public static MyScript Instance { get; private set; }
[SerializeField]
private ScriptA scriptA;
[SerializeField]
private ScriptB scriptB;
private void Awake()
{
// If there is an instance, and it's not me, delete myself.
if (Instance != null && Instance != this)
{
Destroy(this);
}
else
{
Instance = this;
}
}
}``` to access Script A from anywhere: MyScript.Instance.scriptA;
Ah, right. Actually, a Tile is an asset. It doesn't exist in the scene.
if you look at the TileBase docs, it inherits from SO.
https://docs.unity3d.com/ScriptReference/Tilemaps.TileBase.html
Depends on what you're trying to do.
anything is fine i just thought tilebase would be easy because i have a grid based rpg game
i use tile for the floors and walls etc
Thing about the Tilemap system is that it only stores the barebones instance data required for rendering. And it stores it internally.
i want something with good storage like i dont want to do a big matrix of all the tiles
i feel like thats bad for scalability of my game
i want to have a larger board
You mean an array?
right sry
Well, you'd need to use a 3d array or a dictionary. There's no going around it, since unity doesn't do it for you
ok
so it doesnt raise danger flags doing a 3d array alright
as long as i manage it properly?
Error on line 23 of Player.cs which is CS0120. Trying to fix it by declaring line 7 in PlayerStateMachine.cs as static causes CS0176. I'm trying to pass acceleration and top speed values for specific states into the main player's script. I keep reading documentation but it's not clicking on how to fix it. Any help appreciated as I feel pretty hard stuck.
Player.cs: https://hastebin.com/share/ibovigezec.csharp
PlayerState.cs: https://hastebin.com/share/dicuyemayi.csharp
PlayerStateMachine.cs: https://hastebin.com/share/netosuwete.csharp
PlayerDashState.cs: https://hastebin.com/share/ipawanuvac.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i was relying on my instincts mostly that sounded inefficient at first
Yes. Obviously if you have huge/infinite world, you'd need some kind of streaming system or something.
you know people don't memorize error codes
sharing your actual error message would be a million times better
could you give me better terminology for what a streaming system is so i can google ? it just comes up with "streaming services" haha
or a brief explanation would be very helpful
tack Unity to the end ๐
This is what you're meant to do:
float groundAcceleration;
void Start() {
StateMachine.Initialize(BaseState);
groundAcceleration = StateMachine.CurrentPlayerState.groundAcceleration;
}```
Maybe google "level streaming". The concept is the same - loading data from disk or generating it at runtime such that you don't have your infinite world eat up all the memory.
great ty for all ur help i think my solo journey starts here
Noted.
And holy crap thank you.
โค๏ธ
BTW it seems like a bad idea to duplicate this groundAcceleration field
you shouldn't need a copy of it on this script and on the state
it will lead to you having to constantly synchronize it
Yeah I'm confronting that the tutorial I'm following might actually have been terrible the entire time.
yeeeeep
You should just read it from the state whenever you need it
๐
you could make a property to make that easy
Like why have it if I am duplicating the code anyway lmao.
if u learn what not to do.. its still a pretty good tutorial then eh? ๐ซ
private float currentGroundAcceleration => StateMachine.CurrentState.groundAcceleration;```
There's so much bad coding advice online.
absolutely
but the biggest issue is that, you can't take anything as a hard and fast "this is always the best way" rule
not here ๐
real
there are different ways to do almost everything and each is good in different scenarios
Yeah if you do it right the first time you don't have to add more spaghetti to "fix" it.
yup.
, just fact check everything
you'll be a better person b/c of it
honestly this is kind of a myth that beginners believe too.
The reality of software development is that you will be constantly rewriting it as time goes on and priorities and requirements change
unless, ur just a God of hindsight ๐
foresight!
that ^
Well, that is cathartic to hear anyway. Makes me feel like I didn't waste as much time. And it could be argued that it teaches me how to fix it in the future as needed.
absolutely
only worthless if u got no worth out of it.. lol (and u came here for 2nd opinions.. sooo.. ๐ )
oh ur right
its pretty easy
100 percent.. just dont complicate it lol.
singletons are ๐ช
thats why they're typically used for GameManagers, CameraManagers, and whatnot
it isnt u just rename 1 thing to the name of the script ur using then in the script where ur accesing the other script instead of doing S.Money++
you do
Shop.Instance.Money++;
i mean in my case
Yeah, my biggest hurdle has been adjusting things after they've become larger and dependent on one another.
they can stick around.. and hold important data/ call important (GLOBAL WIDE) type of functions
since ur using 1 now.. here's the source material i got that singleton snippet from.. might wanna skim over it just so u have some context about them
https://gamedevbeginner.com/singletons-in-unity-the-right-way/
oh i used a tut lol
im more slow then others and videos make it eaiser for me to understand
IDK if its begginer or not but im trying to learn MLagents and i want to make a 2d flappy bird ai
I get the basics of rewardingรผ actลฤฑbs and observation
How can i let the ai know what to do in flappy bird logically?
like its a weird question but in a 3d movement game
i can teach ai to toucha coin for example
but i cant imagine what to do in flappy bird
get the birds location and the pipes empty parts location maybe? but i cant get it normally because its prefabs as far as i know
I watched a few yt videos and people are using rays but just wanted to ask what to do
sorry for yapping a lot
like dis
Yea, I saw that code monkey guy but its a really hard to understand tutorial for beginners
he is just skipping parts and not explaining enough atleast for me
CodeMonkey has a 2d version
yea yea in that part
Can I use Unity ML-Agents to teach an AI to play Flappy Bird and beat my high score?
๐ฆ Unity Machine Learning Playlist: https://www.youtube.com/playlist?list=PLzDRvYVwl53vehwiN_odYJkPBzcqFw110
๐ Get my Complete Courses! โ
https://unitycodemonkey.com/courses
๐ Learn to make awesome games step-by-step from start to finish.
โ
Get the Project files ...
this one
mmhm im just searching around.. as well b/c idk
https://github.com/xstreck1/flAppy-bIrd heres a github too
np
why is this server so wholesome
You haven't been here long enough