#archived-code-general
1 messages · Page 91 of 1
so, slightly higher stakes there 😛
as the old adage says, there are only two hard problems in computer science: cache invalidation, naming things, and off-by-one errors
Fair, but if you're concerned about deletion, and re-adding. Wouldn't the deletion already cause the issue?
Or do you mean between patches, you delete something and re-add it, before ever deploying?
Yeah.
Hi guys. Maybe someone can advise. Has anyone used dragonBones in their unity projects?
Or if something is removed and then I change my mind down the line
never heard of it
There's no way to overwrite a GUID is there?
Else you could write an editor script to overwrite it
You can override a GUID, but you gonna make every reference in the project go missing.
in this case, that wouldn't be a huge deal, since I'd have already deleted the dang asset
this would be strictly to put an asset back to the right state so that old saves can find it again
Hi guys, i dont know how to explain this, but i want the sphere (it's a particule) to appear as a glowing sphere, but in play it appear like the first pic...
the skybox is eating it!
maybe you need to adjust where it is in the render queue
if it's transparent, but draws before the skybox, then it won't have touched the depth buffer
so the renderer will say "well, nothing's there! draw the sky!"
which render pipeline is this?
where can i check that ? (i'm a beginner)
the answer will probably depend on if this is the built-in RP or the URP
built-in !
so this is from a particle system
yup
so, you should have a Material assigned here
double click on that to inspect it
(also, this is a #✨┃vfx-and-particles problem; let's take this over there)
Its with anything inheriting from UnityEngine.Object
Components, SO's, GameObjects, Textures, materials for example
what with anything? overloaded operator?
iirc only the == is overloaded, something like "is" doesn't work
i've never thought about how is behaves with null values
or "null" values 😛
does null is Foo always produce false?
yes, it's anything derived from UnityEngine.Object . . .
Here you were asking about what class it works on so thought I'd clarify that it is with any UE.Object
I think it's not overloaded and therefore doesn't behave as ==, "is null" will give false even if object is destroyed
right
I'm not sure if the overload spreads to the implicit
if (myObject) or if (!myObject), or to !=
they also overload the implicit bool conversion
it does . . .
hence why if(thing) works
i got confused by how that didn't work with other types at first
i figured that was just How C# Worked
ok makes sense👍
I have a itemClass :
{
public itemType type;
}
public enum itemType {
Consumable,
Equipment,
Gold,
}```
How can i add/make the item to have certain variables based on the type?
Or do i have to create in this case 3 diferent items classes?
3 different item classes
indeed: each one has unique behavior
I forgot what these type of languages are called but c# is not one of them
I guess you could also just give every item all of the functionality
and then just make it so that you can't eat your armor
and can't equip your health potion
Why not just have difference instances of the scriptable object with preconfigured settings?
Can you talk more about that?
I'm assuming you want to simply use one super Scriptable Object and have variable behavior/parameters
items are always tricky bc you can go with inheritance or composition (component-based approach) . . .
Languages like Typescript allow you to dynamically define variables by combining generics and the never keyword to specify variables/parameters/functions that should never exist under certain conditions, but c# does not have that (unless you start using dynamic and expandoObject, but let's never do that).
Normally, you'd create multiple instances of the Scriptable Object and reference them.. leaving which to be used up to whoever manages them instead of having them self manage/change or hold multiple identities.
Got it, and for pecific items that have unique characteristics
I create lets say a specific function of the unique item
How do i "set it" on my chracter?
I cant make ifs for every unique item when the iem is equiped
Is there something like transfering functions?
virtual
class Item
{
public virtual void OnEquipped(){}
}
class Weapon : Item
{
public override void OnEquipped()
{
base.OnEquipped();
// custom weapon code
}
}
class EquipmentManager
{
void Equip(Item item)
{
item.OnEquipped();
}
}
but yeah you can "transfer functions"
that is called a delegate
or you can do something like
class ItemEquipHandler : ScriptableObject
{
public virtual void OnEquipped(Item item){}
}
class WeaponEquipHandler : ItemEquipHandler
{
public override void OnEquipped(Item item) { //custom weapon code}
}
class Item : ScriptableObject
{
public ItemEquipHandler onEquippedHandler;
}
class EquipmentManager
{
void Equip(Item item)
{
if(item.onEquippedHandler)
item.onEquippedHandler.OnEquipped(item);
}
}
sorta strategy pattern
well idk why but it kinda messy
what do you mean messy
enum is an integer
when you are using it normally by assigning integer values like 1,2,10 it is associating that int 2 with some compile time word
but you can use it differently
instead of assigning a whole int value you can assign specific bits in that enum
int has 32 bits, and you are associating specific bit positions
specifically, the enum needs to have values that are powers of 2
1, 2, 4, 8, 16, 32, ...
a power of 2 has a single "1" bit set somewhere, and every other bit is a "0"
each bit starting from left going right is a power of 2 excluding first bit which is one
2^0 is a power of two :p
oh
[Flags]
enum Values
{
None = 0,
SomeVal = 0 << 1,
SomeVal2 = 0 << 2,
}
or
[Flags]
enum Values
{
None = 0,
SomeVal = 1,
SomeVal2 = 2,
SomeVal2 = 4,
}
:0
or
[Flags]
enum Values
{
None = 0,
SomeVal = 0x1,
SomeVal2 = 0x2,
SomeVal3 = 0x8,
SomeVal4 = 0x10,
}
i think you wanted to use 1, not 0 :p
yes
the fact that each bit in the enum int is treated as true or false, means you can combine several values into one
that one ought to be
[Flags]
enum Values
{
None = 0,
SomeVal = 1 << 0,
SomeVal2 = 1 << 1,
SomeVal3 = 1 << 2,
}
this also means you cant use normal integers there
thanks guys
yeah, since 1, 2, 3, 4, ... will have overlapping bits
and it'd be nonsense
so, if you have n bits, you can either store a combination of n values, or you can store one of 2^n values!
i never use this though
combinatorics strikes again
this is easy to understand if you learn how numbers are encoded
assume we have a 4 bit numerical value type
[0,0,0,0]
encode 1 into it
[0,0,0,1]
encode 2 into it
[0,0,1,0]
encode 3
[0,0,1,1]
encode 12
[1,1,0,0]
^
[8,4,0,0] 8 + 4 = 12
xd
thats why assigning 12 to a bitflag enum means flipping 2 bits
which can be desireable
[Flags]
enum Values
{
None = 0,
Wood = 4,
Stone = 8,
WoodAndStone = Wood | Stone,
}
so close to Rock | Stone
is that binary number?
a binary number system has only two digits
decimal has 10; hexadecimal has 16
base64 is 64!
and it will be negative number if reverse
i figure out them on my casio calculator XD
two's-complement my beloved
eh
signed numbers
i reverse them on my calculator and it just become negative
Hello there, I am struggling with RTS Controls... Is there someone who has the will to help me ?
ask the question
yeah, you can combine them like so . . .
[Flags]
public enum DayOfWeek : short
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
Weekday = 2 | 4 | 8 | 16 | 32,
Weekend = 1 | 64
}```
@lethal plank in essense since both bit flag approach and normal int approach are allowed on the enum just by the fact that its an int and all of that is allowed on an int, you need the [Flags] attribute merely to inform unity inspector that the enum is actually bit enum and not normal, the attribute itself doesnt do anything, it is only read by relevant code, like unity, to make decisions on how to treat it
it will become negative if reverse them ALL
0000 0000 0000 0000
0000 0000 0000 0001
is 1
1111 1111 1111 1111
1111 1111 1111 1110
is -1 checked
correct, because you flipped the most significant bit
oh
1111 1111 1111 1111
1111 1111 1111 1110
is -2 xd
Given that i have a scene with different entities (Units, Items, OtherSelectableThing).
The player can select 1+ entity at a time.
The player can select a "Unit", the UI display all the available commands (MoveTo,CastSpell,Attack)
The player choose "CastSpell" command, the UI display a new menu with different spells (Thunder,Heal,Fire)
The player choose "Thunder" spell, the mouse become a target.
The player click on a random location, the spell is casted.
What "Big picture" components would you use ?
At the moment, i have :
- UnitController
- PlayerController
- MoveAbility
- CastSpellAbility
- SelectAbility
- SelectionUI
My problem is, who the hell should be responsible of what in all this mess ? Should the PlayerController handle the inputs logic ? Should the SelectionUI be responsible to buffer a Command object that the Player should execute ? Should the Unit receive the inputs logic once it is selected ?
I've tried so much different since 7 days i'm exhausted
hey, I actually implemented this exact thing like a year ago
I had a lot of "controller" components for sure
actually correct flips them all
I had an "RTS Selection" component that handled the current selection. It had a list of selected units, plus an optional "active" unit
think how Blender handles selection
the "active" unit is the one that gets its statblock drawn and that has its abilities displayed
So you would implement an "ICommandable" interface to each ability of the UnitController ?
I just made everything a Unit
buildings are units that cannot receive move orders
for orders, units have a queue of Orders. They work on whatever's at the head of the queue. Orders can report if they're resolved, and if so, the unit instantly starts working on the next order
orders can create more orders
Alright but, did you split the "MoveOrderAbility" into another controller or was it part of the UnitController ?
e.g. you try to cast an ability, but you're out of range: the unit gets a "move into range" order, then the ability order re-queues itself
did you try treating it as a state machine?
That's handled by each unit, individually.
Orders are not really my problem at the moment, it is more how i build theml
in my system, the order directly controls what the unit does -- e.g. setting the nav agent's destination
I have a StateMachine for the PlayerController
in hindsight, it might have been better to just have the order suggest what to do to the Unit, which then actually moves and stuff
for abilities, I have a single abstract "Ability" class. It stores data about things like what kind of targets the ability can use (units, ground, self). each concrete ability derives from it
when the ability is triggered, it creates an IEnumerator, and the unit then checks that enumerator every frame to let it work (and maybe let it signal that the ability is over)
so, a manually-handled coroutine
Yes, that' what i will do i agree
I made almost everything an ability. Mining resources is an ability!
But my problem is, how do i build my hellish command
what is the problem? code related?
Not code related, it's more like the "Design"
It looks like I gave units orders directly from the selection system
that's an interesting choice, past me!
It has worked out pretty nicely. It was very easy to write an AI system that just gives Orders to units as needed
here's how I handled right clicking on the map
oh, that's missing Act
...you know, this doesn't give much more context, does it
lol
Ok so i see i'm not clear enough with my problem
Let's say i have no problem with the move and act method
My question is, how do you know that you are ordering "Move" and not "ConsumeThisArtifactToInstantlyWinTheGameItem"
Or that you are ordering "CastSpell(SpellKey,TargetPos)"
Why do you need to know that ?
for just right-clicking on stuff on the map, I ask each entity if it has a default "thing" it wants to do to whatever is being pointed at
for example, villager units know that they want to use the "Mine Resources" ability on a resource pile
soldiers know they want to use the "Stab Lots" ability on enemy units
i still dont get it, you have an active context, i.e. primed spell cast, you click the spell cast cmd is sent to unit cmd queue, you dont have any specific overriding ctx active you send move cmd
for left-clicking, that's up to the input manager knowing what state the player is in. if they're trying to cast a spell, then the input manager should know that
Ok, let's say that "Soldiers" can "Stab","Kick" and "DanceAround" ennemies
And that you can control which action you do using "1","2,"3"
Who is responsible to listen for 1,2,3 key inputs
^ For this exact reason @steady moat
you are asking what type of class should coordinate the actions of a unit?
in my game, the input manager knows which unit you currently have selected
it checks if the spell can be casted, and, if so, swaps your cursor and gets ready to cast it on what you clicko n
The player listen to input.
The Unit listen to whatever action you pass to them.
I think yes,
If the player clicks on a valid target, the unit receives an Ability order
the unit then figures out what to do (maybe move in range, maybe just immediately start casting the ability)
equivalently, the AI can decide that it wants to cast a spell, and thus give the unit an Ability order
All I'm trying to do is access the Dictionary but its throwing a tantrum whenever I do, can someone help a lad out
it's null
you showed a small screenshot, so I can't tell what line number the error is from
I'm guessing it's the debug.log line?
if so, AmountHolder is null. fix that.
make sure the object (dict?) is initialized . . .
What do you mean by initialized?
using a state machine with different phases on a manager object would help . . .
unit should be treated as ai agent, with a queue of commands
whatever you call the class doesnt matter much, but it should be an asynchronous fsm/bt
i.e. some orders are synchronous, you cant move while casting, but you can move while shooting, so you the agent can execute 2 non blocking orders in parallel, the orders themselves can contain the code to execute them asynchronously, i.e. coroutines with captured data
that agent code should govern all of the unit components
critically, the unit should not care about user input at all
if it does, then writing AI will be a pain in the arse
in case you will have the player controlling the unit, player controls it through generating commands through ui
in case of AI it does the same, but directly, from the point of view of the unit there is no difference
Thanks for all your replies
i also took advantage of that behavior to let orders generate more orders
that was very very useful for me
the Ability order doesn't need to handle the "walk close enough" logic
there's just a Walk Close Enough order
and a Face The Target order
using new will initialize a collection. then you can add to it or check its properties . . .
yeah you can compose them
this does sometimes cause problems when you have bad logic and it creates infinite orders
oops
Alright so what i have in mind now :
- InputsDispatcher : Listen for inputs, dispatch them to his registered "Receiver"
- PlayerController: Is a "Receiver", he can store informations like "CurrentUnit", "CurrentOrder", "CurrentOrderPosition", and SendStoredCommandToUnit()
- UnitController : Is a "Selectable", "Targetable" and an "Orderable", he can store and execute "Orders"
- ItemController : Is a "Selectable" and a "Targetable", he can store informations about the item and what effects it does when used
- Order : Is a base element to store a routine to execute, and a status
- MoveToOrder : Is a concrete element to store a destination and a navigation routine to execute in order to get a COMPLETED/IMPOSSIBLE status
- PlayerControllerUI : Is a "Displayable", it can display things on the UI given a "PlayerController" regarding its CurrentUnit, CurrentOrder and CurrentOrderPosition, it will display different Things
Approximately
Queue should have its own controlling class solely responsible for maintaining the parallel queues
i just remembered that the unit bt should function on its own
it should process orders when they are available, but the unit is active all the time, and its better to have a bt which is fed orders
that reminds me of one thing I need to figure out: multi-state FSMs
Hello can any one help me figure out what line 6 does
1- public override IEnumerator Shoot()
2- {
3- // ...
4-
5- // What does this line do?
6- yield return StartCoroutine(base.Shoot());
7- }
Am i heading toward a decent architecture or am i completely out of purpose
it starts another coroutine (in this case base.Shoot() and waits for it to complete.
what i mean is that the unit is responsible for executing orders
Unit should be able to play "on its own"
If it had enough queued orders it would mimic gameplay
thanks
I think you've got a decent idea going here.
I'd suggest implementing a basic enemy AI as you do this
it'll help to highlight any bad abstractions
Alright so if the AI can't play easily given my design then i'm wrong implementing
Right.
Thanks for your replies @heady iris @ashen yoke @rain minnow @steady moat
depends on how tight is your ai, in starcraft there is barely anything units are allowed to do outside of input, max they do is chase if they arent holding ground
in that case an fsm would work
rofl, you know, the RTS part is not even the core gameplay
my current AI prototype is mostly weight-based
i'm just giving myself some really bad pain right now 🤣
build town centers near resources and far from town centers
I shoved all of that math into bursted jobs
vroom
Is there a way to run this :
string url = "https://files.rcsb.org/download/" + file_name + ".pdb";
using (UnityWebRequest www = UnityWebRequest.Get(url))
{
yield return www.Send();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
string savePath = string.Format("{0}/{1}.pdb", Application.persistentDataPath, file_name);
System.IO.File.WriteAllText(savePath, www.downloadHandler.text);
}
}
Synchronized? I hate async api, makes the code so unreadable
Or to make a synchronized web request somehow?
well, you can do that if you want to freeze the game...
is this in a coroutine? that lets you write code that feels synchronous
you've got the yield return www.Send() already
I just want it to freeze in this case. It doesnt matter, its not something very important
So what exactly needs to be changed? E.g. www.Send returns an object which does not have any methods to make it force to wait
@ember ore post the full method
public IEnumerable DownloadText()
{
var url = "https://drive.google.com/file/d/1tkZHHgPXT00jqgJPS5FKLEJY5R5688Fk/view?usp=share_link";
using (UnityWebRequest www = UnityWebRequest.Get(url))
{
yield return www.Send();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
string savePath = string.Format("{0}/{1}.pdb", Application.persistentDataPath, file_name);
System.IO.File.WriteAllText(savePath, www.downloadHandler.text);
}
}
}
Wait, can't you just not reffer the trigger or create a separate tag for the trigger?
You can use layer based collisions
Tags don't work?
Tags wont prevent a collision/trigger message from happening
uh, that's goofy, I'll keep that in mind whenever I encounter myself in this situation.
guh???
put the trigger colliders on different layers that are set to not interact
You can also just return if the other collider has isTrigger enabled
But using layers is good when possible, more performant too
@mystic rock
Hello everyone !
I have a question about "how to do things correctly".
In my game, the player has spells that can "curse" an enemy, so some effects happen when they die.
To handle this, I have created a interface (CurseInterface), and spells can create a curse and add it to a list of curse in the Health script of the monster, which will handle calling a function of the curse (defined in the CurseInterface) when the monster dies. that way. I can have monsters explode when they die (because the curse added to the monster has a link to an explosion prefab, which it will instantiate on the position of the monster).
All this works, but I get warnings in the console :
since the curses need to be able to instantiate prefabs in the scene, they inherit MonoBehaviour. But since they're just basic scripts that I want to be able to add and remove to the monsters (some spells curse enemies only while they're in a zone, so they add the curse when entering and remove it on exit), I create them with "new" rather than instantiating a nearly-empty prefab that I would attach to the monster's instance.
Is there a better way to handle all this ?
and how do i do layer based collision
if i do it like this my player gameobject will just fall through the map
put the trigger on a child object and change its layer, then
if you have a Rigidbody on the parent object, then it should still receive the trigger events
or just slap a component on the child that handles them
i use child objects with triggers very frequently
I kinda have to a lot of the times
{
currentQuestionIndex = Random.Range(0, questions.Length);
Question currentQuestion = questions[currentQuestionIndex];
scoreText.text = "Score: " + scoreAmount;
timer = 30.0f;
questionText.text = currentQuestion.QuestionText;
for (int i = 0; i < answerButtons.Length; i++)
{
answerButtons[i].GetComponentInChildren<Text>().text = currentQuestion.AnswerOptions[i];
if (i == currentQuestion.CorrectAnswerIndex)
{
answerButtons[i].onClick.AddListener(CorrectAnswer);
}
else
{
answerButtons[i].onClick.AddListener(IncorrectAnswer);
}
}
}``` can someone help. i have a list of questions each having 4 options and one correct answer. how do i make it so the correct answer isnt set to the same button every time
i tried that but then it sets the answer incorrectly
new Question("This PC is recieving a large number of files from multiple sources, what type of attack is this?", new string[]{"DDoS", "DoS", "Phishing", "Ransomware"}, 0), the questions have a set correct answer
you tried that?
oh, I see
well, you could read the right answer with the index
shuffle the answers
and then find the index that the right answer wound up in
hmmmm ill look into that
thank you so much for expaining, i fixed my code based on ur input ❤️
hey boys
at which point someome can say he's intermediate in programming?
cause everyone seems to know how to do it
and i dont
How would i do this, im kinda stuck lol
at least with List<T>, you can just use IndexOf
assuming you don't have identical string answers
which would be very cruel
i presume you are not re-creating The Impossible Quiz 😛
new Question("This PC is recieving a large number of files from multiple sources, what type of attack is this?", new string[]{"DDoS", "DoS", "Phishing", "Ransomware"}, 0),
new Question("This PC is recieving a large number of files from one source, what type of attack is this?", new string[]{ "DoS", "DDoS", "Phishing", "Ransomware"}, 0),
new Question("This PC has recieved a suspicious email and has sent a similar one to all contacts, what type of attack is this?", new string[]{"Phishing", "DoS", "DDoS", "Ransomware"}, 0),
new Question("This PC has recieved a suspicious Popup that is demanding money in order to open a document, what type of attack is this?", new string[]{ "Ransomware", "DoS", "DDoS", "phishing"}, 0),
new Question("after closer inspection you have determined this PC is being infected by a form of ransomware, How do you repair this?", new string[]{ "Run Antivirus", "Turn PC off", "Pay the fee", "Ignore it"}, 0),
new Question("after closer inspection you have determined this PC is involved in a DoS attack, How do you repair this?", new string[]{ "enable traffic filtering", "Turn PC off", "Run Antivirus", "Ignore it"}, 0),
new Question("Jules has been sent a link to a commonly used website, however the name of the website is wrong in the hyperlink. What should he do?", new string[]{ "Delete the email", "Turn PC off", "Run Antivirus", "Click the link "}, 0),
};``` these are my questions lol
one suggestion
you should make a ScriptableObject that holds a question and its answer
it would look something like
using UnityEngine;
using System.Collections.Generic;
[CreateAssetMenu(menuName = "Question", fileName = "New Question")]
public class Question : ScriptableObject {
public string question;
public List<string> answers;
public int correctAnswerIndex;
}
perhaps the correct answer could always be the first one, to simplify thigns
you could then just have a List<Question> and shove all of the question assets in there
"Ignore it" is a big mood
its for my final project aha, im making a game based around teaching a user cyber security
with that question object do i just copy paste all the questions in?
each question object would store a single question and its answers
right-click in the project view -> Create -> Question (it ought to appear near the top)
you'd need to rewrite whatever used the old Question class, of course
yeah, ive sorted it now
I have a list of all the items with ID order
When i am changing the inventory and applying stats. Should i use the data of the item, or get the data of the item from the list of all items by ID?
DialogueManager.GetInstance().EnterDialogueMode(inkJSON); this is my line 39 why is it giving me this error ?
Is your dialogue manager null?
re: this, I read up on custom converters for the Json.NET package, and I worked out how to completely get rid of the separate "data" struct
the internals are still a little scary to me, but now it just looks like this
[Serializable]
public class Progression {
public UplinkSpec lastUplink;
[JsonProperty(ItemConverterType = typeof(IdentifiableConverter))]
public List<UplinkSpec> uplinks = new();
}
oops, I forgot to annotate the first one..
a save winds up looking like
{"lastUplink":null,"uplinks":[[1913176568,1205621800,3900081345,1309863492]]}
{
if (instance != null)
{
Debug.LogWarning("Found more than one dialog manager in the scene");
}
instance = this;
}``` i have this code so it should not be null if it was i should be tolded by debug
the converter parses the guid and then asks a static class to look that guid up
i wonder if i should just serialize a hex string of the guid at this point, since it's actually better than encoding the four uints...
Use the debugger or just add a debug.log in front of the crashing statement
ok i did that
still doesnt show up up tho in my console so i dont think thats the issue
how do i cut the collider of an object by a bit , but only from the top
and object still acting the same, just with a smaller collider from the top
It doesn't show up in the in the console?
Show code + console
edit the collider size and move top down to lower height
ok
huh?
what size
i don't have any size
No you are saying if not(!) Null
i just got radius, height and center
and for the height i tried editing it but the mesh going trough the ground
Edit the hieght and offset the collider
But I am sure there's an edit bounds button
Looks like 3 squares with lines between them
this is what i do
float newSize = originalSize / 2f;
float yOffset = newSize;
Vector3 newCenter = originalCenter;
newCenter.y -= yOffset;
playerCollider.center = newCenter;
playerCollider.height = newSize;
tried the offset original-new, didnt work
{
if (playerDetected && Input.GetKeyDown(KeyCode.E))
{
DialogueManager.GetInstance().EnterDialogueMode(inkJSON);
}
}
}
No debug.log ;)
is the console not the debug log?
I'm taking about this
Popular function to write something to the console for debugging purposes
didn't work
i tried to edit it's overall offset
still going trough the ground
Do it in the editor and validate by placing your object in the scene manually
You should be able to see the collider outlines
I have a feeling that your piece of code puts the collider through the floor
And as soon as two colliders have intersected, they'll just pass through
yes! that's exactly my problem
so how would i fix that
i don't know exactly how colliders work when changing them
The conpution of your offset is incorrect
i would need original-new, right?
📃 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.
It's awful to read on mobile without syntax highlighting
If you don't add an offset your mesh goed through the floor right?
With about 25% ofbit going through by any chance?
Because I think you need to offset by new size / 2
yes
What you could do, is place your character or whatever entity slightly above ground
So like 5f above ground or whatever
And see where it settles
Because I think now your character would hover above the ground by 25% of your height
So you have to do new size / 2 as offset
That's probably a new issue
OH btw @winged mortar i need newSize/2 because the height-2 is -1 from bottom and -1 from top?
that's how it works?
i didn't think it worked like scale
ye
And then when you use a 1,1,1 collider
It is basically 0.5,0.5,0.5 away from the centerpoint
oh alr
btw
could the shaking be because
i am always changing when pressing a button
i mean GetKeyDown gives true for the duration i have the key down or just once?
well, look at the documentation
https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html
Returns true during the frame the user starts pressing down the key identified by name.
so i tried out post processing for the first time and followed a tutorial but the vignette effect isn't working help
this is what i currently have on my main camera
are you using the built-in render pipeline?
when you created the object, what template did you use?
I'm guessing you're using the built-in one. It's labeled as "Core" in the templates, iirc
right
okay, so that's the first important bit
if you were using anything else, you'd need to use a totally different system for post processing
I actually don't know a lot about the built-in RP's post processing
this isn't a code problem, so it should go to #💥┃post-processing
oh wait thats a channel
also realized there was a beginner code channel whoosp
i shall go there
is it possible to destroy gizmos like debug.drawLine ?
wdym "destroy" them?
they only draw exactly when you tell them to draw
if you don't want to draw them, simply don't.
for (int i = 0; i < questionsSO.Length; i++)
{
QuestionScriptableObject questionSO = questionsSO[i];
string[] answerOptionsArray = questionSO.answers.ToArray();
questions[i] = new Question(questionSO.question, answerOptionsArray, questionSO.correctAnswerIndex);
}
``` am i doing something wrong?
i am only able to set one question object when i need 7
i need 7 questions in the array however in the inspector i am only able to set one question
what's stopping you from setting more?
this code doesn't have much to do with the inspector btw
What is this picture showing?
1 question? Show the definition of QuestionScriptableObject.
Seems like you declared it as a string instead of an array or list of strings
public QuestionScriptableObject[] questionsSO;
tis is not what you';re looking at abive
this is in some other class
what script is this in>
am i supposed to declare the scriptable object in its own script?
Yes
then how do i access it in another script?
though the little snippets you've shared here are too small and scattered for me to make heads or tails of what you're doing
through fields like this
generally
the scriptable object is a class. instances of that class can be stored as assets. you can reference those assets.
declare this (or maybe a List<Question>) wherever you want to use the questions
and drag the assets in
when i declare that it says it cant be found?
Well if you haven't declared something called Question then yeah
basically we are all confused and guessing because you haven't shared your code
you called it QuestionScriptableObject
or at least not enough code for us to make sense of what you're doing
im an idiot
I'd rename it while you're at it
rename the script in Unity
so that it understands that the new script is actually just the old one with a new name
and then change the name of the class
I haven’t seen any mention of this, but does Unity mind reflection? Or is it going to tank performance?
there's nothing special about it in Unity, afaik
other than if you're using code stripping in IL2CPP builds
since it can be hard to tell that you're using a method if you only ever call it through reflection
it's gonna be less performant than just calling the method normally
Hay I have a set of tiles and want to draw a outline of a specific color around a area of them to denote the range of say attack distance or movement range but I have no clue how to even start could anyone point me in the right direction?, i can already detect and get a list of tiles that will make up the area i really just have no clue how to draw a line around them, moved this here from urp cuz i don't really know what section this would apply to
and it's tile-based, rather than being a smooth circle?
Yes, this image is a example
the first thing that comes to mind: you have a set of tiles that you want to outline
each tile draws a line if that neighbor isn't in the set
(for all four neighbors)
oh right, and that's how you'd get the set of tiles, by searching :p
sorry noticed he said he already has the list
Hi! I'm having a bit of problems with my camera and I'm not sure why it's happening. Currently, my camera can see through the terrain at most angles even though it isn't actually under it. It's set to orthogonal and I've tried messing with the distance but it's almost always showing something under the terrain. I've also made a script to prevent the camera from going under the terrain but for some reason it always looks under it.
orthographic, you mean?
What's your near clipping plane set to?
the near clip may be too far, yeah
but basically - for an orthogonal camera - you'd have to make sure the entire near plane of the camera isn't clipping through the terrain anywhere
it can be non-intuitive, since we're so used to perspective views
okay, issue is how would I draw said line, I get the logic of each tile checking if it's neighbors are in the area and then drawing it bassed of that, just dont really know the method of drawing it.
naively, I'd just use a ton of line renderers or sometihng
I'll try changing it, thank you!
0.2 is pretty close
Here's a possible algorithm which you can combine with a LineRenderer:
https://stackoverflow.com/a/56285291
Oh did not know line renderers were a thing, thanks
i'm not sure if using hundreds of line renderers would be a Good Idea (tm)
Yep. That worked. I set it to -40. Thank you!
hundreds probably not
i didn't know you have a negative near clip
i guess it makes sense for an ortho camera
that should be roughly equivalent to pulling the camera 40 meters back
yeah if you're gonna do this you might as well just move the camera back
I didn't know that was possible either
alright so im now back to where i started but with a scriptable object. so my problem is ``` private void SetQuestion()
{
currentQuestionIndex = UnityEngine.Random.Range(0, questions.Length);
Question currentQuestion = questions[currentQuestionIndex];
scoreText.text = "Score: " + scoreAmount;
timer = 30.0f;
questionText.text = currentQuestion.QuestionText;
for (int i = 0; i < answerButtons.Length; i++)
{
answerButtons[i].GetComponentInChildren<Text>().text = currentQuestion.AnswerOptions[i];
if (i == currentQuestion.CorrectAnswerIndex)
{
answerButtons[i].onClick.AddListener(CorrectAnswer);
}
else
{
answerButtons[i].onClick.AddListener(IncorrectAnswer);
}
}
}``` how do i shuffle the buttons but keep the answer to the correct text so for example if phishing ismoved to button 1 it is still correct
because at the moment my problem is the answer button will always be the same so index 0
Could giving my tile prefab a line rendering and then setting it appropriately when i need to draw the outline be a god way of doing it?
question with line renderers, when I set a position, what is that relative to? is it world space or is it relative to the pivot point of the object the component is attacked to?
like say I have a 1x1 grid tile with a line renderer on it, how do I draw a line from the top left to the bottom left of that tile?
!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.
there's a checkbox in the inspector for this
i think it defaults to world space
thanks, ive figured out that the error in this is because the newCorrectAnswerIndex is being set to -1 anyone got any idea why that would be - https://paste.ofcode.org/LHDVnwSF5f44Prt7jX6RcL
you'll probably want to turn that off. you can then figure out the right coordinates by just slapping an empty child on the tile and moving it around
look at the local position (the position shown in the inspector)
how do i see coliders in the scene view when running
no, i have nothing on gizmo to show me
no, in preferences i cannot find gizmo either
and no, i am not using an older version to not have those features and the proprieties of the collider don't have show feature
Gizmo => make sure colliders are checked
okay cool i found it, although is there a way to directly see and edit the position of each point of the line like with numbers in the inspector?? NM found it
I have a list of all the items with ID order
When i am changing the inventory and applying stats. Should i use the data of the item, or get the data of the item from the list of all items by ID?
hello
I wanna make that when a player enter the server call him player1 and when another one enter the server call him player2
but im having trouble
how to see if every gameobject in a gameobject array is disables
The property you want to check is activeSelf. Loop through your array and individually check for that property.
If you find one that's active, you can break out of the loop as an optimization trick
yeah how do i do a for loop
That's something you would Google
if you don't know how to do a for loop, then you might need to do some more basic C# lessons..
did i do it right
for(int i =0; i < EnemiesInWave.Length; i++)
{
if (!EnemiesInWave[i].activeSelf)
{
nextWave.SetActive(true);
}
}```
my goal is to make it so that if every gameobject in the array is disabled it enables the nextWave gameobjet
this checks if one object is disabled
Yeah that doesn't check if all of them are disabled
perhaps you should declare a bool that's set to true, then set it to false if any object is not disabled
It checks all yes, but not whether they're all off
the cute way:
if (EnemiesInWave.All(e => !e.activeSelf)) {
nextWave.SetActive(true);
}```
The inverse, all disabled to switch to next wave
yeah
also, a useful tip
"true if all disabled" has the same meaning as "false if any are enabled"
my suggestion turns it into the second one
Yeah this is equivalent to:
if (!EnemiesInWave.Any(e => e.activeSelf))```
Yeah it's better because it bails out as soon as the first element that doesn't match the condition is found
there's some latin name for this
they will both bail out early
i just found a bunch of new weird symbols on wikipedia
Discord LaTeX support, when
DeMorgan's Law perhaps?
ah yep, that's it!
looks occult :/
looks occult 🥳
Yeah De Morgan's is used to invert boolean expressions for example
A • B => !A + !B
I never finished my comp sci degree, but my absolute favorite coursework was translating parts of the US constitution into propositional expressions for a "discrete mathmatics" course
It was just sort of pleasantly mind-bending
Hey, I'm looking for a quick and dirty solution to decoupling some of my code.
Short explanation, I have a panel that has some code in OnEnable to randomly generate some selectable objects on it. This panel is default inactive to be hidden, but can be pulled up from multiple sources. Instead of referencing this panel is all these places, I wanted to try activating it with an event Action. So that the panel is hidden and just listening for when it needs to display
could someone tell me why this works only if im trying to connect from my pc to my pc but not from my phone to my pc(im trying to send sensor info to untiy)? https://pastebin.com/8WvnqTa5
an event is triggered by the object that owns the event
so you'd need to have the panel register itself with all of those event-holders
what error(s) do you get?
Obviously while it's inactive, it's not listening, so I tried putting the listener in a script on an empty parent, but now some of the OnEnable/OnDisable code is reacting funky...
none
then wdym it's not working?
Also where is this code running?
and where's the code that sends the data?
show your code, I guess -- I am unclear what's going on
!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.
You just mean subscribing to the event, right? += DoCode ?
right
absolutely no errors it just doesn't want to connect from my phone to my pc. it works only on the local device.
code that im using on my pc:
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('192.168.1.102', 2555)
client_socket.connect(server_address)
message = "hi"
client_socket.sendall(message.encode())
response = client_socket.recv(1024)```
Yea, I have it subscribed, but I think because it default state is inactive/disabled, I don't think that's working until it's been turned on once
show your code; I can't guess what you're doing
this looks like... python? How are you running it on the phone?
Ok, sorry. Give me a few min. Thanks
im using a app called hyperimu on my phone(for sending the sensor data) and that code on my pc for testing
Are you sure (0.0.0.0) is the right IP address to be listening on? tcpListener = new TcpListener(IPAddress.Parse("0.0.0.0"), 2555);
isn't it normally 127.0.0.1 ?
that would only listen on localhost
thats for local
so other machines on the network couldn't talk to it
exactly
is your phone connected to the same local network as your PC?
ofc
idk you could be on 5G ¯_(ツ)_/¯
on mobile, in general :p
this is not a unity problem, so i'm not sure you'll get a ton of help here
I blamed potentially not being in the same local network
but yeah this seems like a general networking problem at this point
its the code sense my python version of the server works fineeee
i am confused
so your python server works fine, but you have some other server written in C# that is not fine?
Button to display the panel on the left, inactive panel on the right.
Also why not this?
listener = new TcpListener(IPAddress.Any, 2555);
so, i had a python server i used. but then i realized i cant use that in unity so i made a c# version of what is essentially the same thing(the c# version doesnt work)
im going to try that but i dont think it really matters sense 0.0.0.0 is just scanning thru the entire network
Maybe it's Unity that's blocking it? Have you tried running the server from a good old console app
actually yea
!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.
i dont remember if it worked ;-;
Gotta check again, then
what's the problem here?
A network analyzer like Wireshark could also see if packets are being exchanged
i just did it like this
void Update()
{
int number = 0;
for(int i =0; i < EnemiesInWave.Length; i++)
{
if (!EnemiesInWave[i].activeSelf)
{
number += 1;
}
}
if (number == EnemiesInWave.Length)
{
nextWave.SetActive(true);
}
}```
ill change it to that rn
that's a lot more code and somewhat less efficient but that does work.
yep, that's just beginner version of code that @leaden ice has suggested
Error CS1061 'GameObject[]' does not contain a definition for 'All' and no accessible extension method 'All' accepting a first argument of type 'GameObject[]' could be found (are you missing a using directive or an assembly reference?) Assembly-CSharp H:\unity games\fps game thig\Assets\Scripts\wavescriptthingy.cs```
add the using directive
System.Linq
I'm trying to decouple some some code and remove some references. Here's my original question:
"Short explanation, I have a panel that has some code in OnEnable to randomly generate some selectable objects on it. This panel is default inactive to be hidden, but can be pulled up from multiple sources. Instead of referencing this panel is all these places, I wanted to try activating it with an event Action. So that the panel is hidden and just listening for when it needs to display"
ok thank
can you send your code than?
yep the regular c# server works but not the unity one https://pastebin.com/LxdstUS2
Yeah requires linq else cs foreach(var e in EnemiesInWave) if(e.activeSelf) return; nextWave.SetActive(true);
I don't know the best way to send multiple files, but I split it up I guess
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.
that's nice
although I do not see your issue here
Yep looks like regular server code to me.
How are you implementing that in Unity? That has a few while loops that will freeze the game. If you're running it on another thread then know that you can't use most of Unity functions there, or you'll get your thread silently killed
Also I'm assuming you debugged a bit and that you know your code is executing
I don't think this works because the panel is inactive by default. I'm trying to figure out a way to enable it through an event
How i implemented it? through shear pain and suffering... jokes aside. im sure the code is executing. it might be unity thats blocking something idk.
so you do not know how to find inactive gameObject in the scene?
📃 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.
oops, already mentioned
Events is a regular C# thing, it doesn't care that your object is disabled. Your event handler WILL run if it's subscribed whatever the state of the object is
i walked across campus, so I'm getting caught up :p
I am always here to mention it
i scrubbed through the chat a little too fast
So you definitely can enable objects with an event, given that the target object has subbed to it, and that the event is getting invoked
Ok, so the issue isn't that the object is inactive then, that's a start. Thank you
Awake won't run until the component is active
Ok, so there's the disconnect I'm missing
do you need to find non-active GameObject with a script?
Also on line 17 you have some exotic syntax, is that intentional? Where you toggle that boolean
Lol, yes that was intentional. I saw it somewhere as a quick way to toggle. I'm assuming there's a better way?
It works, so no problem here
i'd just do gameObject.SetActive(!gameObject.selfActive) or something
I guess? That's kind of what I'm here to figure out. Obviously my original approach isn't going to work, so I'm looking for a better way to do this when that panel might be triggered from multiple places.
I'll take a look at that. I definitely like that better. thank you
then:
GameObject yourSmth =
FindObjectsOfType<GameObject>(includeInactive: true)
.First(w => w.CompareTag("TagThatYouNeed"));
That's exactly what they want to avoid, coupling
Hence the use of an event
Plus that piece of code is quite convoluted, FindObjectWithTag exists
no
that's wrong
you cannot find non-active GameObject with FindObjectWithTag or Find
you can try though
Well pretty sure FindObjectOfType GameObject is also wrong because GameObject isn't a component type
And even if it works, it's not pretty
no
that's the best solution that works
the current script requires a direct reference to the button, so I'm not sure that's much better..
unless you do not want to drag you gm
if there's going to be more than one panel, then someone is gonna have to hold a reference to someone
it could be that the buttons know about the panel, or that the panel knows about the buttons
@simple egret I wonder if you can suggest smth better without dragging gameObject into the scene 🤔
what?
what?
what "what?"?
I mean I understand some referencing is necessary, I was just trying to find a better way to do it since I know I'm going to have multiple different ways of opening that panel. The button in the pastebin is just the first one I've been working on. If the easiest and cleanest way to do it is just to make a direct reference to the panel, then that's what I'll do.
that's what you should do.
I was just hoping to learn a better way is all I guess
the button needs to know what it's targeting
that's a very reasonable way to tell the button what to target
use an event on the button if many things need to listen to a single button
That makes sense... Event when it's more listeners, not more sources
I like making some simple script to manage a bunch of UI/canvas stuff and putting it on a parent object.
That way I can hide/unhide panels and stuff all I want since the script is on a diff object. (often on parent)
Why calling NavMeshAgent.ResetPath produces an error if you call it when the agent is disabled or not placed in a NavMesh? How can I reset the path in those situations? I know that path doesn't work in those situations... but as soon the agent is enabled or placed in NavMesh again it will recalculate the path. Instead, I want it to forget the path.
you could try agent.path.ClearCorners()
The path still exists
I want to make reusable cast bar, what are the best practices for telling other components that casting has been finished, any help would be great 🍻
For presentation-only things like UI the best approach is to use events.
I.e. the thing that does the spellcasting fires off events and the UI listens to those events in order to display what it needs to
this allows the spellcasting thing to have zero knowledge of the UI stuff
Thanks, I'll try with that, also no spellcasting, only reloading and hacking 👀 🍻
did you try SetPath with an empty path?
Oh, will try
If i have a script Dog on my gameobject which is a child of Animal, will calling gameobject.getComponent<Animal> give me the Dog script?
yes
Yes, and this even work with interfaces, so if you do GetComponent<IAnimal> it would also work, which can be handy sometimes
awesome ty
the big brain move: GetComponent<Component>
i guess that could give you the Transform
Hello, using the new input system, how could I go about getting a reference to a device from one player input and manually making another player input use that device?
How should I handle having a hitbox for the character as well as having a generic hitbox for tool usage (sword, pickaxe, etc)?
I tried having two BoxCollider2D, but I don't think that works?
Does it require having a child script?
If you need to distinguish between two colliders or two triggers, then yes
i personally use a physics query (like overlapbox) for tools since they don't necessarily need to always be looking for collisions
true
could you expand on this a bit? I'm not familar
well first, do you know what a physics query is?
What is the best way to make game saves for survival game? How map looks, player inventory, what player had build on map etc?
nope 😅 time to learn
oh like, raycasting and such?
yeah, that's exactly it
oh wait, why do tutorials suggest box collider rather than just doing overlap query
overlap query seems way easier
a lot of tutorials are not good or show things the lazy/easy way.
although one question I'd have is for example in a sword swing, an enemy could walk into the animation after I do the overlap query
there's a few things you could do, if you're actually using an animation for the sword swing I would create some animation events at key points in the swing, the events will all call the same method that uses the overlapbox or whatever query you decide to use, then you could either just immediately damage the enemies when they are first detected, or you could add them to a list/set (HashSet to prevent hitting the same enemy more than once) and at the end of the animation have another event that applies the damage and clears the list/set
there are also other ways you can handle it of course, but i generally find these to be a good balance of easy to set up but also fairly accurate without relying on collision messages
I'll try that! definitely seems nicer than having a child object just for another collision box
one of the biggest drawbacks is that you won't actually be able to visualize where the physics query is though. so you'd have to either draw the gizmos yourself or use a debugging library for it. personally i use this one: https://github.com/vertxxyz/Vertx.Debugging
should also clear up the collision issues I was having earlier where i couldn't hit an enemy while attacking unless i moved between swings
i can just copy my boxcollider2D size and offset right?
sure but it's harder to see if you actually got it right without actually visualizing it in some way
true
i'm relatively new to unity, I was working in ue5 before so I appreciate the help
i think part of my complexity is coming from the fact that I'm making a Character class and 3 subclasses for each character type (goblin, skele, human) and they have different logic
one thing I wish was cleaner was animations
I feel like my system is ... not great
i basically just have a "animation broadcast" system
and so then the skeleton, human, and goblin each have animations to match all of those (except skele who only has a few)
i have to send it to children, because otherwise the hair, and tool animators don't animate properly
you may want to consider checking the docs pinned in #🏃┃animation and learn how to set up transitions and the like so you don't have to manually call Play with specific strings and can instead just pass data about what the object is doing to the animator and let it handle switching to the correct animation states. just my opinion though 🤷♂️
wouldn't quite work with 20+ animations
well it could, but it'd look v awful
► Easily make Platformers using my Unity Asset - http://u3d.as/2eYe
➤ Ultimate 2D CarGame Kit [ON SALE] - http://u3d.as/1HFX
➤ Wishlist my game - https://store.steampowered.com/app/1081830/Blood_And_Mead/
➤ Join the community - https://discord.gg/yeTuU53
➤ Support on Patreon - https://www.patreon.com/lostrelicgames
0:00 Escape Unity Animator ...
so i followed this recommendation of just running my own
https://docs.unity3d.com/Manual/AnimatorOverrideController.html
You've got these too if subclassing is the problem
i switched to Animancer, personally
i like when everything is code
i don't use animations to make things rotate; i just calculate it in a script
He seems to be doing exactly what Animator was created to resolve - not having to code or manage the transitions of your states (once set). Where Animation behavior is decoupled and we'd basically throw flags to attempt state changes. I'm not a fan of the UI and the Animator visually but this doesn't feel like the correct approach.
I don't see how animator makes sense when there are animations that can be called from any state and then need to return to their original state, especially for top down 2D frame based games
Like every single animation state needs a transition to "character_take_damage" in that case
fun fact, you can have multiple layers in your animator
They're rules. You set them and abide by them. Same with properties etc
It makes sense when using 3D models, but if you're using 2D sprites and skipping the transitional frames then just calling the animation is fine
I don't buy that, even with layers if I have 100+ animations it seems way tedious to have 100 animations rather than just play(takedamage)
Some folks want public access to everything, static everything and whatnot.. which are very efficient for specific tasks but these are technically boiler plates.
His hard-coded strings had a negative impression on me.
Changing stuff in Animator would require you change stuff in the script.
But there isn't anything in animator to change
Ideally, you'd want to write code once and not have to change it.
The state names
Then you'd have to go through all of your scripts and change every string name etc
Transitions don't make sense when every animation can lead to almost every other animation
For 2d, it'd be useful a bit as blends aren't necessary
You get n^n transitions
indeed
especially when some animations can go to some animations, and there're enough that you really don't want to manually write every single transition by hand..
I don't disagree with that. I'm just not likely his setup.
I would love something better
Well, you're never going from a dig to an attack animation usually
it's dig, to neutral, to attack
Input buffer could make this happen
If you queue up an attack during the dig
It simply feels like.. cs private int score; public int Score {/*Convoluted stuff*/}where you'd not use properties there if things were simple but it'd be redundant to have those procedures implemented by the caller.. this is so backwards 
Sometimes simple is better but his illustration was mostly (imo) an appeal towards ascetics or those who are struggling to use Animator the normal way.
My biggest struggle is that the superclass is dictating what animation the subclass should play and as such the super class needs an explicitly defined non changing set of animations
Cause all characters have health and can take damage but then they all have different damage animation sprite sheets
And sure you could make it some kind of dictionary that the child has to implement but you're still just calling animator.play
And then on top of that each character has different logic to go with each type of animation because a skeleton does more damage than a goblin or something
My setup definitely doesn't seem ideal
Maybe I should just make my character superclass an interface?
But I'm not necessarily sure what that would clean up
So.... I went to sleep for a while and closed unity, when I came back I found this 😄
ok I think I figured out what's causing me pain
my Human character object has a body sprite, a hair sprite, and a tool sprite
previously I had the body sprite on the parent so it was like
Human - Body Sprite
--- Hair - Hair Sprite
--- Tool - Tool Sprite
but it seems like it'd be easier if I moved body as a child
am refactoring everything right now, not sure if it makes sense, would appreciate y'alls thoughts
using UnityEngine;
interface IDamagableEntity
{
// All entities have health
int maxHealth { get; set; }
int health
{
get
{
return health;
}
set
{
value = Mathf.Clamp(value, 0, maxHealth);
if (value <= 0)
{
Die();
}
}
}
// Functions
abstract void TakeDamage(int damage);
abstract void Die();
}```
using System.Collections.Generic;
using UnityEngine;
interface ICharacter : IDamagableEntity
{
// All characters can move
bool canMove { get; set; }
float moveSpeed { get; set; }
// All characters have movement input
Vector2 movementInput { get; set; }
// Collision detection
float collisionOffset { get; set; }
ContactFilter2D movementFilter { get; set; }
List<RaycastHit2D> castCollisions { get; set; }
// All characters have a rigidbody
Rigidbody2D rb { get; set; }
// All characters have animator(s)
List<Animator> animators { get; set; }
// All characters have sprite renderer(s)
List<SpriteRenderer> spriteRenderers { get; set; }
void flipSpriteX(bool flip)
{
foreach (SpriteRenderer spriteRenderer in spriteRenderers)
{
spriteRenderer.flipX = flip;
}
}
}```
it's sleeping
shhhh
What's a better way to do this?
public enum AnimationState
{
Attack,
Axe,
Carry,
...
Watering
}
// Dictionary from AnimationState to string
public IDictionary<int, string> animationNames = new Dictionary<int, string>();
animationNames.Add(AnimationState.Attack, "attack");
animationNames.Add(AnimationState.Axe, "axe");```
am trying to have it such I can use enums, but it seems kind unideal
Thinking I could have some kind of JSON file, but then its not type safe
enums are fine, and you can break them into categories too if you want
pretty much the basis of a statemachine
yes, but then I also need to create a dictionary that goes from int to string so I can then play that animation
just feels very roundabout
Seems fine by me if you dont want to explicitly write the string when you swap states
why do you need to link int to string for animations?
change your animation names to match your enums
when you call animator.play() it takes a string
yes but why do u need an enum/int associated with it and why in a dictionary
You can do enum.ToString()
And it'll give you the name, make sure the anims match that ;)
if you're going to look it up with AnimationState.Attack, why not store the animation name as a const string?
i did this before and had 20 consts
you're gonna have the same thing as an enum and then in a dictionary
but if u want it in 1 data structure instead then its fine i guess
I'll do enum.tostring ig
Should cache the results to avoid expensive repeated operation!
how would I cache it, dictionary?
lol
back to dictionary
Let me re-read above. There may be another solution.
What's the relationship between your enum and the <int,string> dictionary?
Are you using that to compare the enums.toString()?
all I want to do is animator.play(ENUM)
and then it converts to the right string
so i can avoid typos with my strings
dictionary is love
It sounds like you can get away with using scriptable objects instead?
that all seems like overcomplicating it compared to just 20 constant string variables
the 20 consts just look ugly
i care
I think you're over engineering this?
the exact same functionality, and no dictionary lookups just for 20 extra strings. not even 20 extra lines, because ur enum will need each string anyways
Establish minimum requirement of your game first. Prove the concept. Demonstrate what makes your game fun and enjoyable with primitive geometry and simple animations.
All of the fancy stuff can sit right on top of that principle of rules you made.
What good of a game if it can't function over how good you optimized your enum to string collection?
right now I'm not making a game
I'm mainly just trying to learn unity, I'm familiar with unreal, fullstack, etc
🤔 you mean c#? because this whole string business is not related to unity one bit
c# and unity's specific frameworks yes
You have some C++ background. Now that I see it your perspective.
You are overcomplicating the design.
Unreal and Unity have some similar concept that you can translate over, but unity takes thing less descriptive than unreal.
i went ahead and switched it over to constants
Instead of relying on enum, you can instead use scriptable object to help further customize your game. Start something small and grow from there.
Also, if these are named states in your animation you should convert and cache them them to a hash using https://docs.unity3d.com/ScriptReference/Animator.StringToHash.html and that's what you pass to the animator
another dumb question for y'all
wouldnt scriptable object be overkill for this particular thing
What would cause it to prevent me from creating a subclass?
I haven't had issue before, but feel like I'm missing something super basic 
... what is the error
The type or namespace name 'Character' could not be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]
What's in Character.cs then 👀
using UnityEngine;
abstract class Character : MonoBehaviour, IDamagableEntity
{
// All characters have a rigidbody
Rigidbody2D rb { get; set; }
// All characters can move
bool canMove { get; set; }
float moveSpeed { get; set; }
// All characters have movement input
Vector2 movementInput { get; set; }
// Collision detection
float collisionOffset { get; set; }
ContactFilter2D movementFilter { get; set; }
List<RaycastHit2D> castCollisions { get; set; }
bool tryMove(Vector2 direction)
{
if (direction != Vector2.zero && isAccessible(direction))
{
rb.MovePosition(rb.position + direction * moveSpeed * Time.fixedDeltaTime);
return true;
}
return false;
}
bool isAccessible(Vector2 direction)
{
// Cast a ray in the direction of movement
int numCollisions = rb.Cast(direction, movementFilter, castCollisions, collisionOffset);
return numCollisions == 0;
}
// Health
public int maxHealth { get; set; }
public int health
{
get
{
return health;
}
set
{
value = Mathf.Clamp(value, 0, maxHealth);
}
}
}```
Bizarre. Does the error exist in Unity, and are all these files saved?
relaunching everything, once sec
ah that might contribute
ah yeah, vscode errors are super janky sometimes
importing system generics works
Hey, im struggling to do some logic if the string is same as it was last time the function was called
oldText = null;
var note = oldText += Notepad.GetText;
mewText += note + "Added";
if(newText == Same as oldText)
{
bool = true
}
here is a very simple example, I cant get anything to work, any ideas? And yeah I do know about String.Equals
I'll keep trying, but if you have an idea please suggest it
I'm making a attack on titan fan game and when you grapple onto a wall, I want the camera to slightly tilt towards the grapple point on the z axis so that the camera tilts when you swing around a object however I'm not sure what the best way to do this is. I tried making use of the LookAt function and limiting it only to its z axis but I get janky results when it comes to looking around since I think its using global rotation. What's the best way to achieve this?
List<T> is from System.Collections.Generic
I'm trying to draw a boarder around the tiles in an area and I got this but if the if the true if statements aren't consecutive it leads to lines being connected to each other where they should not, any thoughts on how to fix? or what might be a better way to do this?
example of the problem (the diagonal lines and also the top most tile having a line across its bottom)
so i have some portals but i'd like to turn them off if they're occluded by geometry. I could use raycasts but i'm not sure where to cast from or where to cast at. i was thinking cast from each corner of the bounding box toward the camera but i'm not sure if that'd work?
I want to have animation events in the children that call functions in the parent, is that possible?
or do I need to make mini-helper scripts for each to enable that
So i've been trying to teleport my player and it's just not working, what am i doing wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class tpPlayerOnLevelLoad : MonoBehaviour
{
private bool hasTeleported = false;
// Update is called once per frame
void Update()
{
if (!hasTeleported)
{
GameObject teleportLocation = GameObject.FindGameObjectWithTag("teleportLocation");
if (teleportLocation != null)
{
Debug.Log("trying to tp");
GameObject player = GameObject.FindGameObjectWithTag("Player");
if (player != null)
{
player.transform.position = teleportLocation.transform.position;
Debug.Log("teleported player");
}
else
{
Debug.LogWarning("No object with the 'Player' tag found.");
}
Destroy(teleportLocation);
Debug.Log("deleted the tp location");
hasTeleported = true;
}
else
{
Debug.LogWarning("No object with the 'teleportLocation' tag found.");
}
}
}
}
Not sure if this question should go in here or in editor-extensions, but I have a custom icon on a script that is annoyingly huge in the scene window. Is there a way for me to have that script not show it's icon on top of GameObjects it is attached to in the scene window?
Character controllers behave weird sometimes
Try disabling the cc before you teleport
and re-enable right after.
@dim skiffThis also doesn't need it's own class. You're going to screw yourself up by making every little thing into it's own class
i see, ok
You should create a function for it, on your main character
it was a part of my roomManager script, that is always in my level, but it was breaking, i thought it was because it was trying to teleport on the same frame that the teleportLocation was insantiated, so tried to put this script on the room prefab so it starts after its loaded in yk
how would I make a character point in a direction? All the sources I find don't involve looking toward a specific direction and are just about rotating.
THIS WORKED !!!!!! TYSM !!!!
I am using I tutorial to do a inventory system so I can learn more coding and something I see pop up often are =>
Example: [SerializeField] private List<InventorySlot> inventorySlots;
public List<InventorySlot> InventorySlots => inventorySlots;
public int InventorySize => inventorySlots;
Can anyone explain what it does
in order to point in a direction you have to rotate (unless you mean smth else entirely) . . .
it's a newer syntax (sugar) to create a property. this is a getter (read only access) . . .
https://ransomink.notion.site/Properties-The-Real-Estate-of-C-77979cb0108b4a1ba3b1d16ef301b264
Read This When You're Ready to Code
So is
public int InventorySize => InventorySlots.Count
The equivalent of
public int InventorySize()
{
return InventorySlots.Count
}
yes, but the bottom one is a method, not a property. all of these do the same thing . . .
public int InventorySize => InventorySlots.Count;
public int InventorySize
{
get => InventorySlots.Count;
}
public int InventorySize
{
get { return InventorySlots.Count; }
}```
hey, this is weird
public enum Type
{
A = 0,
B = 1,
C = 2
}
public Type type = Type.A;
.... // later
Debug.Log((int)type); // 604 ?????????????????????
what 604 means ???
anyone alive ?
What's the debug right after you assign it
fixed it , nvm , i was debugging a different variable
^^
is there a way to call the camera to only render the depth texture, execute some code, then render the color channel?
is there a way of accessing unity's occlusion culling stuff to check if an object has been culled?
Implicit cast from NativeList<T> to NativeArray<T> has been deprecated; Use '.AsArray()' method to do explicit cast instead.
Why?
I'm trying to do occlusion stuff where a portal turns off when you can't see it with the camera. i tried casting a ray to see if it's occluded but there were too many raycasts that it made a bigger impact performance then always having the portals on. does anyone have any ideas on how i'd do this?
an idea i had was to check the cameras depth texture to see if anything was occluding but that'd not quite work
because i'd only be able to check the render texture from last frame, and the occlusion might've changed since then
i'm quite stumped.
occlusion culling doesn't work either because i'm handeling the rendering of the portal myself
Using the depth texture from last frame is quite all right. Occlusion info wont change so drastically from frame to frame. It’s good enough for nanite heh
is that what nanite uses?
the depth texture method would have a single frame of the portal being visable but not on which would break the illusion of the portal being an extention of the space instead of an actual portal
Well thats why you make your bounding volume conservative. I e a bit larger than the portal
That way it will be registered as visible a bit before the actual important part is
Sure you loose a frame or two of perf
But if your portal effect is that heavy consider optimising it
it's mostly just the camera rendering
until i figure this out i'm just using frustum culling + having small levels so every portal outside the level disabled
You could use the culling group api
So that if the portal is out of main frustum disable portal camera
mm that's what i was thinking but i'm unsure how it works
I'm not sure if it's going to work because the portals have no mesh renderer
This handy repo does all of the work for you https://github.com/mackysoft/Vision
I'll look into that, thanks
You dont need a mesh renderer the culling group uses a bounding sphere to do the check and you receive a callback where you can do your custom logic
I'm trying to make it so that the red rectangle will be clamped from 90 to -90 on the while looking at the mouse on the left side. However, the rectangle will only look to the right side. Switching the 90 and -90 only makes the rectangle look at 90 or -90. Does anyone know how I could solve this?
Me and my friend are working on a game that is tempo-based.
Currently, I’m keeping tempo in a singleton, then having a Boolean value either be true or false based on if the current game time is on or off best.
This works in theory, but Unity has some variance in update times, so it’s a little wonky. Initially, I had a timeSinceBeat value that kept reference of the most recent beat, though if one got off sync, then all others would be basing off of the off sync beat, so it’d slowly fall out of time.
This was fixed by keeping total time and referencing that instead since I can know where the next beat should land.
The issue is, beats are always either too fast or too slow due to the way updates work. Right now, I’m checking if(currentTime >= timeOfNextBeat - some fudge value), but this results in beats that are either too fast or too slow. If I remove the fudge area, it’ll still result in beats that are too slow. I’ve attempted this in both Update and FixedUpdate, but neither are as precise as I need. What’s a good solution to this?
Ideally, I would check if(currentTime == timeOfNextBeat), but currentTime may never be that value since it will most likely skip that exact number within a single update
@knotty cargo welcome to the world of rhythm games 🙂
https://www.gamedeveloper.com/audio/coding-to-the-beat---under-the-hood-of-a-rhythm-game-in-unity
I'm trying to understand how to properly code edge tolerance to my 2D game. Any advice or tultorials that may help?
Also I didn't felt it at first but that optimization in the camera is god's bless upon plataformer gamedevs, I came back to my project 3 days after I added, played and felt great.
Hello,
how to I call method TupleRange of this class in my another Unity Script ?
using UnityEngine;
public static class Helper
{
private static float TupleRange(this (float min, float max) tuple) => Random.Range(tuple.min, tuple.max);
}
someTuple.TupleRange();
I guess I should write using Helper, but it does not work
is it problem with unity or lack of my c# knowledge?
It is private 🤔
oh.
it was the most stupid question ever. thx @hexed pecan
All good lol. I never thought of adding extension methods to tuples so I learnt something
yeah, that's quite convenient if you have smth like this:
private ((float min, float max) x, float y, float z) spawnPos = ((-4.3f, 4.3f), -1f, 0f);
private (float min, float max) flyForce = (10f, 14f);
private (float min, float max) torqueForce = (-20f, 20f);
Sure, is there a reason youre not using a struct though?
Might improve readability IMO
But I get it tuples are fun to use
Input system, Invoke Unity Events, happened to trigger on both when i press left mouse button and when i lift my finger from the mouse.
Hello everyone !
I am currently designing a spell called "Rain of Arrows" for my 2D game. it's what you would expect from the spell :
the player aims its mouse with a circle previewing where the spell will happen, then clicks, and arrows rain on the circle-area.
I want the arrows to fall randomly in the area, and I would like for each pixel to have the same chance to receive an arrow hit, so the spell is useful against hordes of enemies in a wide zone.
I am currently thinking about HOW to randomly determine where the arrows should fall, and I was originally thinking about determining the position like this :
Vector2 arrowOffset = Quaternion.Euler(0,0, Random.Range(0, 360)) * Vector2.up * circleRadius;
with arrowOffset which would be added to the position of an invisible prefab created where the player clicks their mouse (the center of the circle).
There is a problem with thie method : there will be more arrows in the center, and fewer on the exterior.
I made a drawing :
There will be as many arrows in the Red as there will be in the orange (and as there will be in the yellow).
Do you guys have an idea on how to have the random more spread out, while keeping it in a circle (so no simple Vector2(Random.Range(0, sideLength), Random.Range(0, sideLength)) ???
Input system, Invoke Unity Events, happened to trigger on both when i press left mouse button and when i lift my finger from the mouse.
How to make it only work when i only press it?
what's wrong with the simple thing? Reject the point if it's not within the circle and regenerate
I feel like "rejecting the point if it's not in the circle" in a complicated check for nothing. Especially as I want my "rain of arrows" to create 50-100 projectiles.
but maybe it's not, with a simple sqrMagnitude
Maybe have two different circles, the smaller one would base their arrows more in the area that you want
the larger one would cover all of it but with the chance of it hitting the middle as well
Or do three circles like your images and divide the arrows evenly
oh, or are you asking you want them completely spread out?
then you can use this
oh wow, I didn't know this existed ! 😄
There's no 3D version of it sadly but I've written something similar for it if you need that instead
Oh, there is also a 3D sphere overlap too
oh, I see. I can actually do one [Serializable] struct Tuple for all tuples
it should be better though
multiply the circle radius then get rid of any points outside the original radius
or just do this nvm
does somebody know how do I serialize struct from another struct without refering to this class?
private Helper.Tuple myTuple;
// how to do this?
private Tuple myTuple;
Take it out of the type it's enclosed in
This worked :
do {
arrowOffset = new Vector2(Random.Range(-rainCircleRadius, rainCircleRadius), Random.Range(-rainCircleRadius, rainCircleRadius));
} while (arrowOffset.sqrMagnitude > rainCircleRadius);```
But I went for the simpler
```Vector2 arrowOffset = Random.insideUnitCircle * rainCircleRadius;``` and deciding to let Unity what my random would be 😄
A type that's used outside the one it's nested in, shouldn't be nested in the first place
are you reffering to me? I do not get you
Yes
I don't get the issue you're having though, then
Can you post an example of how these types are structured
using System;
namespace Helper
{
public static class Helper
{
[Serializable]
public struct Tuple
{
public float min;
public float max;
public Tuple(float min, float max)
{
this.min = min;
this.max = max;
}
}
public static float TupleRange((float min, float max) tuple) => UnityEngine.Random.Range(tuple.min, tuple.max);
}
}
I will be changed soon, but for now I can access it just like:
private Helper.Tuple tuple;
By the way, is there a way to know the source that's behind simple I call from Unity classes ?
Yeah so struct Tuple, out of the static class
thank you!
The unity code of the class? Not sure about it anywhere online, but vs studios will usually grab you some decompiled code if you right click and find the implementation
Thats all the engine Unity C# code
If it's in the C++ side then you're out of luck
Editor -> Mono is where the main stuff for the editor is
I only get the signatures of the functions
Can't find the code for the Random functions
I've been asking this fow a few days but still no answers... I thought it was a general plataformer concept but even searching a solution on google was not easy.
eh, too bad, I'll use the function, and not know whether it's the random type I want, but as long as it works and does not lag, I4m good.
😢
Some talk about it
and how to make it even more random
Ah, this is with a minimum radius if you want that
I'm trying to clamp velocity for the x axis of the player using this:
void FixedUpdate()
{
if (rb.velocity.magnitude > maxspeed)
{
rb.velocity = Vector2.ClampMagnitude(rb.velocity, maxspeed);
}
}
but because of this the character is unable to fall fast on the y axis because it clamps both the x and y
how do I clamp just the x axis?
use mathf clamp
oh wait nvm its clamp magnitude
then that might not work
record the previous y value and apply it?
my movement system right now is using AddForce to make it more floaty and make it have to accelerate
alr
you can still use rb.velocity =
to limit the speed
addforce for speed limiting wouldnt work
rb.velocity = new Vector3(rb.velocity.x, 0, rb.velocity.z);
but wouldn't that make it so that my character would float?
var vel = rb.velocity;
var clamped = Vector2.ClampMagnitude(vel, maxspeed);
clamped.y = vel.y
rb.velocity = clamped;
no
although you might want to clamp just x, your code will clamp overall magnitude which is probably not what you want
yeah
oh this is working how I want it to