#archived-code-general
1 messages · Page 160 of 1
F2 ??
it works in code
how can i get the array of them?
"them" ?
idk what are they called, the game objects that are recorded in the animation
using AnimationUtility class
tyy
have a look on this method
if you just post the link as is, it is easier for everyone to see what you post
and correct/add to what you are discussing
I see, you can see link by clicking on it
it will give you "Leaving Discord" message
ill just ignore posts like that, its easier
good for you
|| why || || is || || it || || good || || for || || me|| ?
for me and everyone would be good if we didnt have to jump hoops just to see what links you post
can you elaborate whats the idea behind posting link like that? what does it serve? what function
Its more compact, especially if your link is long
Doesn't really bother me or most people i know tho
(also hovering the link just shows the URL)
Is this messy code?
void changeVelocity(bool forwardPressed, bool backwardPressed, bool leftPressed, bool rightPressed, bool runPressed, float currentMaxVelocity)
{
//if player pressed forward, increase velocity in z direction:
if (forwardPressed && velocityZ < currentMaxVelocity)
{
velocityZ += Time.deltaTime * acceleration;
}
// increase velocity in backward direction:
if (backwardPressed && velocityZ > -currentMaxVelocity)
{
velocityZ -= Time.deltaTime * acceleration;
}
// increase velocity in left direction:
if (leftPressed && velocityX > -currentMaxVelocity)
{
velocityX -= Time.deltaTime * acceleration;
}
// increase velocity in right direction:
if (rightPressed && velocityX < currentMaxVelocity)
{
velocityX += Time.deltaTime * acceleration;
}
// decrease VelocityZ:
if (!forwardPressed && velocityZ > 0f)
{
velocityZ -= Time.deltaTime * deceleration;
}
// increase VelocityZ:
if (!backwardPressed && velocityZ < 0f)
{
velocityZ += Time.deltaTime * deceleration;
}
// increase VelocityX if left is not pressed and velocityX < 0
if (!leftPressed && velocityX < 0f)
{
velocityX += Time.deltaTime * deceleration;
}
// decrease VelocityX if right is not pressed and velocityX > 0
if (!rightPressed && velocityX > 0f)
{
velocityX -= Time.deltaTime * deceleration;
}
// stops the running, when you just press Shift alone without also pressing "w":
if (!runPressed && forwardPressed && velocityZ > 0.41f)
{
velocityZ -= Time.deltaTime * deceleration;
}
}
it just feels like a way to long "if, if, if, if, if, if, if, if, if" chain...
quite
any ideas to improve this mess?
Compose your input into a vector (every beginner tutorial on movement will show this), and use that as your direction to accelerate towards.
Its using the new input system and should be compatible with Keyboards and controller joysticks.
new input system doesnt return a float?
havent used it yet, does it behave similarly to GetAxisRaw("Vertical") for example?
int VelocityZHash;
int VelocityXHash;
void Start()
{
VelocityZHash = Animator.StringToHash("Velocity Z");
VelocityXHash = Animator.StringToHash("Velocity X");
animator = GetComponent<Animator>();
}
I also did it with hash to improve it hopefully.
how is this related
the player is a humanoid model. and besides the player movement, this script is for adjusting the walking animation of this humanoid model. keyboard WASD is just a 0 or 1 value, but a joystick is capable of multiple speeds between 0 and 1.
this script is not doing the player movement, it only affects the animation and the animationspeed of it.
But the playercontroller script does handle the new input system movement like this:
Vector2 movementInput = _controls1.Player.Movement.ReadValue<Vector2>();
float xInput = movementInput.x;
float yInput = movementInput.y;
(but this is not the problem, the problem was the messy if statements in the animation script of the player-model)
you can do several things, first is to predeclare the booleans with conditions
9x if for the two dimmension animation controller.
move duplicate lines into a single variable ie Time.deltaTime * deceleration;
use a single vector
combine all ops into one vector, mult/add at the end
convert input values into -1 /0 /1
I'm not sure how to apply that into this here...
I want to make a game with thick fog like this to obscure vision (like in SH1.) How was that done?
sorry was busy, something like this```cs
void changeVelocity(bool forwardPressed, bool backwardPressed, bool leftPressed, bool rightPressed, bool runPressed, float currentMaxVelocity)
{
float accel = Time.deltaTime * acceleration;
float decel = Time.deltaTime * deceleration;
int vertical = (forwardPressed ? 1 : 0) + (backwardPressed ? -1 : 0);
int horizontal = (leftPressed ? -1 : 0) + (rightPressed : 1 : 0);
int verticalClamp= Mathf.Abs(VelocityZ) < currentMaxVelocity ? 1 : 0;
int horizontalClamp = Mathf.Abs(VelocityX) < currentMaxVelocity ? 1 : 0;
Vector3 velocity = new Vector3(VelocityX, 0, VelocityZ);
Vector3 accelerationVector = default;
accelerationVector = new Vector3(horizontal * xVelocityClamp * accel, 0, vertical * zVelocityClamp * accel);
decelerationVector = new Vector3(-Mathf.Sign(VelocityX), 0, -Mathf.Sign(VelocityZ)) * decel;
decelerationVector.x *= horizontal == 0 ? 1 : 0;
decelerationVector.z *= velocity == 0 ? 1 : 0;
// stops the running, when you just press Shift alone without also pressing "w":
if (!runPressed && forwardPressed && velocityZ > 0.41f)
{
velocityZ -= decel;
}
}```
didnt finish, and didnt test wrote in notepad
looks smaller, but more complicated too.
agreed, this is inferior, in some regards
Is ": 0" inside of the (forwardPressed ? 1 : 0) a second if statement?
There a a few combinations and letters I dont know.
is ". 0" a repeat of the same question "fowardPressed ?"
IDK it but it looks for me like it (but I dont know this code condiction)
Look up ternary operator
This is a weird one to choose the channel for as it is about animation but the problem I'm having is related to script.
PROBLEM
after switching the player model animator only works after manually interacting with it.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Also even after manually updating the animator the animation rigging ik on the gun seems to lag behind
and what does "?" mean?
converts a bool into 1 or 0
so true is 1 and 0 is false
you can also use it to convert it to other values such as strings
but why "?"
I know that "!" means "is not" but what is "?"
or
maybe
its only used in this context
The conditional operator ?:, also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false.
(https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator)
And what is with the good old "==" ?
If it is true, otherwise....
Well, ternary operators need to have the other part
:
And they are better used in assignment of values in one line(and still keep it readable) instead of using a if clause
it just seems that "?" does have the same effect like "=="
"==" means: "check, if it is same like... then (YES), if it is not the same, then (NO)"
bumping this
condition ? //If true: //if false
This has an effect as a smaller if else clause
It's not ==
Well only a part of it is
Equals() and ==
Would give you the same results but it's better to use Equals() with non-primitive types
does anyone know why my monster sprite and character sprite are overlapping even if the z is 0 and fixed for both?
ones always gonna be infront, rn is prob the order you've added them in?
just change order in layer
also not code question
alr thanks
bumping again, also discovered that it also works after saving a script.
but hell, thats complicated as F....
int vertical = (forwardPressed ? 1 : 0) + (backwardPressed ? -1 : 0);
why even "1 : 0" ? Why not "true : false"?
and what does "+" mean?
is it something like the common "&&" between two if statement conditions?
can you go to code0begginer
i am so lazy to read the code snipper sent from .cache but you can simply try all combinations
if both are not pressed then you get 0+0
if forward then you get 1+0=1
if backward the you get 0+-1=-1
if both are pressed you get 1+-1=0
But they dont have all the history and background information of it.
thats always the problem with switching channels.
but your asking what the + variable means
I think it means the same like "&&".
have you read my reply?
your adding the bools together after they get converted from a true to false to a int 1 to 0 for forward and -1 to 0 for backward
Bumping
I did not even noticed that it was converting something,
^
the bools in this case are forwardPressed and backwardPressed
Show me the part of the code where you call this void
oh i see
the first of my if statements (in my version) was:
//if player pressed forward, increase velocity in z direction:
if (forwardPressed && velocityZ < currentMaxVelocity)
{
velocityZ += Time.deltaTime * acceleration;
}
I dont see here anything that would be converting, or am I wrong?
why dont you use Input.GetAxis("Vertical") and Input.GetAxis("Horizontal"). Is it cause your using a different input system
I use the new input system
It's part of the ternary operator. Please look it up
Don't provide ai generated answers please
aight then
the script I used, was from a 2 year old Unity project that I already cancelt, I only was visiting it to get some information's about a few old scripts in there that I want to recycle for my current project.
´Because I think it would be maybe usefull to know a if-statement alternative that needs way less codelines than the common if condition...
The only issue with it is, I don't really understand it cause it uses some letters I saw and never used before.
"?" and "+" are new for me, cause I never used them in the programming.
what languages have you coded in that dont use +
maybe asm.....
I never used more complex conditions that simple if, switch, while, for conditions.
but they sometimes need way more space, even if it also works.
the only high level languages I found that dont use plus are brainfuck, whitespace, befunge, Ook and malbolge.
i remember brainfuck have +
increment the current memory space by one
I took a example from my old script and asked here how to improve it, because I had no idea to get the same results of it with less lines of code. that why we are here with ternary operator.
I only use C#
I would be glad if I even would understand this single language good enough.
So thtas why you should be in code begginer
but I dont think that "ternary operator" are beginner contents, if I look in this channel.
Beginner stuff is such content like if, while, switch....
ternary operators are complex as hell if I look into your GPT script.
It's beginner and you are a beginner. The bigger issue here is you thinking reducing the line count on your bad code will make it good code.
You need to change the approach to your movement which means scrapping what you have.
bumping
https://gdl.space/potufuyeze.cs why does the bomb spawn with gravity? I have been trying a couple of bools to make sure it works and also have set everything to the correct layers, but somehow it will just spawn without gravity. Does anyone know why? The colliders are also set correctly.
I cant figure out how to program jump on my "man" character how should I do it?
apply a vector3.up force when u press a certain key like space
check for ground and ^ then do that
yes very important do a raycast check else u can infinite jump
just run into an issue where I was cloning a renderers sharedMaterial and assigning it back to the renderer's sharedMaterial, then another script (not mine) was calling renderer.material.SetXYZ, resulting in my clone being cloned. I guess assiging to .sharedMaterial flags the renderer as no longer having a copy material, which made me wonder if, apart from at edit time, should I ever assign materials to .sharedMaterial? Would assigning my clone to .material have the same affect but without affecting the instanced material flag?
can I post code here If im doing everything right?
do !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.
does anyone knwo why? Im super confused. and also i set it in the inspector to use gravity incase anyone thinks its that
I also asked GPT even he says he doesnt know why
looks correct to me
I would use a raycast to check if its grounded but that works too
If it doesnt jump try increasing the groundcheckradius
so in the unity component inspector thingey should I create an empty gameobject at the players feet and then select it as the ground check position?
I would either do it with a raycast or a trigger collider
I fixed it btw. Somehow there was a clone spawning on the ground triggering the gravity.
is it possible that other scripts are making it not able to jump
is it set to isKinematic=true? kinematic rigidbodies dont respond to respond to forces
If they are using .velocity it might be ioverriding it
It wasnt that, I basically wanted a sticky bomb so after it tocuhes the floor or walls it get kinematic. But the clone was triggering the gravity and kinematic so to me it seemed like the script was somehow triggering it
ok so it doesnt quite work but I know why it wasnt working it was because I had a script were the player character was always on the same Y level as the camera
because of weird bugs
now I can infinitely jump I will change that but for some reason the ground is not stable
what should I do to make it stable
PROBLEM
after switching the player model animator only works after manually interacting with it or saving and then compiling a script.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
ive been trying to use the job system to help the performance on my dungeon generator but i cant seem to get an output from the job here's the code that runs the job https://gdl.space/oqefurudax.cpp and here's the code that is the job https://gdl.space/enifanisit.cs
are you trying to new a managed array in job?
no i dont think so but im not entirly sure what u mean
bool[] neighbors = new bool[8];
im making an array of bool in a function to determine what kind of sprite to use rotation ect but I'm not trying to get that value as an output
there are 3 native arrays one for the rotation(int), sprite(int), and cellposition(int3) that i need as an output
there should be some exceptions are thrown when you try to run the job due to allocation o f manage object, have you checked the console?
theres a ton of index out of range exeptions
the capacity of all native array you passed to the job should be width*height not height*height+width
and the first nested for loop should be x*width+y also the second nested for loop
and the arguments of job.schedule should be height not width
bump
for the managed bool[] array you may change them to fixed size buffer in struct and reuse them
unsafe public struct AAA{
fixed int aaa[10000];
}
what dose the unsafe part do?
and the cs int randomRotation = UnityEngine.Random.Range(0, 4);you need to use Unity.Mathemathics.Random struct
you can use pointer in unsafe content (fixed size buffer is some kind of pointer)
how do i use the unity.mathmatics.random cause im assuming its not the same as the unity engine one
i really need help here, so i have a movement script that stop working when i kill or deactivate one istance of a gameobject using it
^
i have 4 instances of a prefab using this script and when i kill or deactivate one all the others stop working
okay i may have found the problem, aftre one is deactivated all the others stop registing inputs
i still get thoses index out of range exeptions at this line rotationArray[x * arrayWidth + index] = rotation; wich is at the bottom of job function right before all the methodes
it should be index*width+x, but i see all indexer are this expression
for accessing [i,j] element the indexer is i*width+j normally unless it is column-row format
when i instantiate an object with a monoBehaviour script, does it call Awake() immideatly?
ye
what if i need to set some fields there
It's Awake() then start()
before Awake
The update of the mono should not run until next frame, so implement a init function
if i call a function, will it be called before or after first Update() ?
depends when you call it
right after Instantiate only Awake and OnEnable will have run
Transform obj = Instantiate(...)
obj.GetComponent<Script>().field = ...
when will it be called?
when will what be called
when will it set the field
right there
on the second line
also why not just cs Script obj = Instantiate(prefab); obj.field = ...
so you said after Awake, what about start and update
there is still index out of range exceptions theres 8 of them with very slight variations. IndexOutOfRangeException: Index 20035 is out of restricted IJobParallelFor range [100...119] in ReadWriteBuffer. IndexOutOfRangeException: Index 4113 is out of restricted IJobParallelFor range [20...39] in ReadWriteBuffer. those are 2 of the variations
are you sure? i'm getting null references in start
then you haven't assigned something
or you assigned something to null
Add Debug.Log if you don't trust me
you will see it runs later
you're right thanks for the help
Does anyone know why my button here wouldn't be working? I'm not sure what I'm doing wrong. I'm just trying to use a normal UI button and call a method on click
you don't appear to have an EventSystem in the scene
also not a code question
Oh ok, thanks. I'll go in the other channel next time lol
hi, does anyone have an idea how I can add a delay to WallGrab and WallSlide during the jump, because so far the character walking towards the wall catches it, which makes it impossible to jump? CODE: https://gdl.space/asiwideviy.cs
have you changed the arguments passed to schedule? @loud flume
from width to height
why, this has never happened before why
yes, basically u add a bool at the if statement that you made for jumping, basically" && IsReadyToJump" , then after you jump you set that bool to false, and either invoke a function in there or make it all a coroutine its up to you, but simpler is just to invoke("PrepareForJump" , Time);
right after the jump, and what u want that function PrepareForJump do is set the IsReadyToJump to true, and there u have it
same thing with the wall grab and basically everything that you want to limit, bullet shooting etc.
ok will try to do that, thank you🔥
yw
can you give more details?
its part of my weapon script and its to rotate the weapon away from walls to stop clipping
RaycastHit hit;
float weaponRotTarget;
if(Physics.Raycast(weaponAvoidRay.position, weaponAvoidRay.forward, out hit, weaponAvoidDistance))
{
weaponRotTarget = -(weaponAvoidMaxAngle * (weaponAvoidDistance / hit.distance));
}
else
{
weaponRotTarget = 0;
}
Debug.Log(weaponRotTarget);
transform.localEulerAngles = new Vector3(Mathf.Lerp(transform.localEulerAngles.x,weaponRotTarget,weaponMoveSmoothness*Time.deltaTime),0,0);
I've added fev lines of code like this (idk if its good): https://gdl.space/mebeduyuja.cpp , unfortunately, despite adding the delay, the character still bugs in the corner the same and still trying to grab the walls :/
I'm making a ground visual effect and i want to make it work on stairs. Basically i need to project a shape on stairs. so i think it comes down to finding stair border points like in the image. How would i do that? or maybe you have a better idea
what kind of effect are you talking about
you can imagine it as dynamic road
I don't know what that means
generates a road over time based on where i'm looking at
what does that have to do with stairs? And what do you mean by "a road"?
you can say it paints the ground
so what's special about stairs?
yes
turn the get node return arry[(y + 1) * arrayWidth + x]; to arry[y*width+x]
Hi guys, I'm trying to make a player have a small cutscene to jump into a teleporter every time he presses "e" on a teleporter. Where could I do that, or would I have to hard code that in. (Sorry if it sounds confusing, I can re-explain if you'd like) This is unity 2d
i'm working in 3D. It generates a mesh forward until direction raycast hits a slope, then it projects the direction and keeps going. It needs to work similarily with stairs.
One thing I would suggest that may help a bit (but may not outright solve your problem), is to try and make 1 call to .velocity instead of having every part of your logic try and set it, they can instead set a Vector2, and after all calculations, that vector2 can then be passed to .velocity - I would also maybe add some Debug logs or make some events for each part of your problematic logic (in your case, jump, wall grab and anything else you think could be a conflict, maybe gravity?) then you can use UI to see when its changing, or make properties in the inspector to monitor the change - to me, it looks like your movement may be affecting y velocity, gravity could still be active in the frame your grabbing or jumping, or coll.onWall may be causing conflicts with wall grabin the frame your colliding, moving and jumping against the wall
there still index out of range exeptions
is the exception showing the line?
also the boolean check of getnode is x<width not height
still this line rotationArray[index * arrayWidth + x] = rotation; and there are exactly 8 exeptions eveery time
first this question probably goes into #💻┃code-beginner
also did you ever put any actual code ? because you do need to code it in. idk what you mean "hard code"
i havent use ijobparallefor indeed but from the exception it seems that it is not allowed to use a for loop to write different index of native array (since you are using [index*width+x] and x is iterator)
i believe reading a readonly containers is allowed (the bool nativearrays) you can try passing width*height to schedule and retrieve the row and column from the index passed to execute()
I've coded the movement and animations of the player and the teleporter, however, I am trying to make like a short animation of an interaction between both at the same time. I don't know if I need to make the player get pulled toward the teleporter, I wanted to see if there was an easier way
so instead of doing a for loop and having a job do one row of the dungeron grid pass in the index being used and remove the for loop for the x at the start
though idk why these indices 20035 and 4114 are produced, the different between them is huge most likely the expression in indexer is wrong
yes, dont do this row by row, just cell by cell so no loop in execute()
also there are 40000 cells so idk why 20035 and 4114 would cause and index out of range
You could code it with coroutines for timing and lerps for movement, or if the cutscene is always going to be the same, you could maybe create it with Animation keyframes and animation events, or you could try to build it with Timeline, and maybe Cinemachine if you need more editing tools to create your cutscene, I believe you can also extend Timeline with code
and you access the result array directly by result[index (the argument of execute)]
so should i continue to use ijobparralefor and just change it to work with a single cell at a time or use ijob for that
i think you have to write more code if you want to change it to ijob
just stick to parallel unless other exceptions are thrown
what should i pass in for the index
what index?
for getting row and column in execute? or schedule?
can someone help me with my dash? it doesnt work well
or well
at all
doesnt work at all its just really weird
the keybind for dash is e
for schedule but im assuming its just the ammount of cells
canDash = false;
isDashing = true;
float originalGravity = rb.gravityScale;
rb.gravityScale = 0f;
rb.velocity = new Vector2(transform.localScale.x * dashingPower, 0f);
yield return new WaitForSeconds(dashingTime);
rb.gravityScale = 6;
isDashing = false;
yield return new WaitForSeconds(dashingCooldown);
canDash = true;
oh crap
thats the dash function
schedule(width*height,some batch number)
you need to execute width*height times of execute since you have width*height cells
ok the main reason i made it go line by line instead of cell by cell is because of the getnode function because to find which sprite and how it should be rotated i need to know variables of the neibors but if its just a single index i couldend think of a way to find which indexes are the neibors
you can get the row and column from the index passed to job by index/width and index%width respectively
using ijob maybe faster since you can get rid of / and % (if width is power of 2 then fine) but you need to write some more lines of code
What is the context of this code. Looks like it's a coroutine.
Also, you cache the gravity scale, but then set it to 6 instead of using the original, which I find interesting
Also, you can cache those waitforseconds instead of creating new ones each time
yes it's a coroutine, also I really don't know why I put 6 lol
Can you show the code where you start the coroutine?
yeah uhh
can I send it in a pastebin
the whole code
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.
Yeah, but there are ones specifically for code I would recommend. Like:
Hastebin.com
Or
Gdl.space
Ah, nm haha
so if i need the y value of the cell i need to do index/width cause i feel like that wouldent work becuase if u have a 10x10 grid for example and want to get the cell index is refenceing if index is 1 and both the width and hight are 10 you do 1/10 wich is 0.1 for the x and 0.1 for the y and if say u needed to refence the point 2,0 i feel like u couldent find that cause ur using one input index and trying to get 2 outputs by dividing with the same number
does anyone know why this IMGUI code from docs doesn't work? The window is not draggable for me. I'm using 2022.3.5f1 https://docs.unity3d.com/Manual/gui-Controls.html
/* Window example */
using UnityEngine;
using System.Collections;
public class GUITest : MonoBehaviour
{
private Rect windowRect = new Rect (20, 20, 120, 50);
void OnGUI ()
{
windowRect = GUI.Window (0, windowRect, WindowFunction, "My Window");
}
void WindowFunction (int windowID)
{
// Draw any Controls inside the window here
}
}
Ok, so it's a new input callback. You have others that work, so I would say just check to make sure the dash one is set up properly, and that you clicked save or have autosave enabled.
Just to start with, because the code looks fine at first glance
since the index = some row*width+some column then you can retrieve row and column by / and %
i did already
Yeah, on watching that video, I see it halts you in the air, which proves it IS working somewhat (by setting your y velocity to 0, or maybe it's the gravityscale change)
for(row=0;row<height;row++){
for(column=0;column<width;column++){
index=row*width+column;
}
}
for(index=0;index<width*height;index++){
row=index/width;
column=index%width;
}```
ugh, thanks, didn't think to check that page. the intro page should be fixed
I think that's the gravity scale
and 1/10 is 0 1%10 is 1
i understand now i thought u were saying divide for both row and colum for some reason
Yeah me too, edited that in after I first wrote that haha
Thanks
In your Dash coroutine, you have rb.velocity = new Vector2(transform.localScale.x * dashingPower, 0f);, but you also have rb.velocity = new Vector2(horizontal * speed, rb.velocity.y); in Update, for your x, is it possible your overriding your Dash change with the Update change, and go nowhere horizontally because of it?
i have a setup that loads into my game's menu and it does this by having most of it persistent .. since its a splash screen it only has the BOOT_CANVAS object that doesn't need to.. so currently i just tell my loadmanager to go ahead and destroy it.. since from here on out we'll only need what we threw into DDOL..
so there are no error when it runs now and it generate sprite but i mess the dungeone generation code up somewhere but i should be able to fix that
private void LoadMainMenu()
{
// This method is specifically designed for loading the MainMenu scene.
// It handles the loading and unloading of the MainMenu scene independently.
// MainMenu should not be added to the scenesLoading list as it has a different loading process.
if(FirstLoad)
{
SceneManager.LoadSceneAsync(MainMenuSceneIndex,LoadSceneMode.Additive);
foreach(var x in purgeList)
{
Destroy(x);
}
FirstLoad = false;
}
else
{
...
}
}```
the method bugs me... since it leaves behind an empty array.. / gameobject if i wanted
should i just put the Boot Splash screen in its own scene.. and load it up during the the Master scene
I would maybe put a script on the splash screen canvas, and have that script destroy the object when its done, removing the script, splash screen, and removing the need for the 1-element array if you dont plan to populate it with anything else, normally I have a "initialization" scene as scene 0 to handle the splash screen, authenticating, loading settings, etc, then never load that scene again, having my menu as index 1, in your case it sounds like you want all of it to be in the same 1 scene, so you could just destroy the part of the scene you no longer need - though why is most of your main menu apart of DDOL?
Destructable _des = collision.gameObject.GetComponent<Destructable>();
if (_des != null) {
//do stuff
}
}```
i know there is a way to skip the if (atleast in code) and go directly to the execution in the brackets but cant remember the syntax
can someone help me
yea, i was thinking about having a simple script that destroys itself, but the loading screen has progress bars and varies in time.. so i'd need a reference to it one way or another.. this is the first scene of the game, it loads in all the managers, the audio stuff, settings save data etc, it also has the player object and that data so it first loads into the mainmenu, and then into other level scenes as well, so everything in it, apart from the graphics DDOL.. anytime i load into a scene it does it async, with the loading screen coming down as a curtain
easiest way i think would be to have the graphics as a seperate scene and unloading it after starting the gam
anyone know why it takes so long for an accelerometer to respond
i tilt my phone, and at least a second goes by before it's triggered.
TryGetComponent probably is what you mean, you dont skip the if but you dont allocate if the object isnt found
loosening the conditional values doesnt really help it either
there was something with =>
That's lambda declaration, you dont need it here
why
oh wait
{
if (fooFoozy)
return;
// Code that will only execute if fooFoozy is false (not skipped by the the conditional)
DoSomething();
}
maybe u mean an early return? and inverted conditional? iono exactly wat u meant 🍿
TryGet was my 2nd thought
Lambdas are basically just used as syntatic sugar, to write shorter code when we really dont need to specify a whole bunch. Even if you could use a lambda there, the compiler is just gonna turn it around into pretty much the same thing you wouldve written with try get component
In this case the lambda might compile into something worse tbh
Wouldnt your initialization logic happen before you need to handle your loading screen? If you need to destroy this after your loading screen is done, you could setup a "onComplete" event and have your initializer subscribe to it, though it seems like it would be a weird dependency unless I may have misunderstood what you meant
private void OnCollisionEnter(Collision collision) {
if (collision.gameObject.TryGetComponent(out Destructable _des)) {
_des.Push(transform.position);
}
}```
i think i got it now
i see
so its a compile reason
Well not really, you just dont need a lambda there
but you say the compiler wuld change it
that was the problem tysm it works now
theres actually no intialization happening, just some gameobjects it checks if is there, but it would be checking if all the game managers and audio is present, (game initialization), im actually not very good at structuring these things lol, its just some coroutines counting atm.. but my save system and most the others are singletons that set themselves up.. my "loadingscreen" is basically just a title screen, during the boot up, but becomes the fast travel, in between loading screen after u pass the mainmenu.. when you load a scene thru its functions it checks for a (scene initialization) its similar to the game one, but sets up lighting, enemies, pathfinding etc..
heres an older version of the alternate function of the loading screen
You would only really use a lambda if the statement was like 1 line, like a function or property just returned data directly for example
int x =5;
Public int X=> x;
Im typing on mobile so forgive if theres some error.
The above lambda is just a getter for x. I could write out the whole property and get but in this case I'd rather just use the syntatic sugar to write it for me.
In your case I only really mentioned the compiler because of something called closures. If your lambda has to reference some local variable, it may end up making a new class (you'll never see it) with the variable stored inside. It's not worse on performance in any way that you'll ever ever notice, it's just like an unnecessary usage
its just part of the master scene (all the important persistent stuff) that i load in first thing.. i wish i knew a better way that didn't undo a whole lotta work but alas im 'managing'
bool fooFoozy = ...; // Some condition that you want to check
fooFoozy?.DoSomething() ?? return;```
this ^ is crazy looking syntax to me does this work?
i see, thanks for the explanation, atleast now i know that => is called lambda
like dis
i forget what those fancy combined symbols were called
Lambda declaration is the actual symbol
Lambda is kinda just a general term for the whole thing
no but i mean the "text/ character" name
its not glyphs, maybe it was this.. i cant find it
I'm unsure, dont even think mine combines like that
the font ur using has to support it
and theres some setting that you enable (maybe)
Ligatures 🙂
i was looking for this
function = (condition) => {execution}
is this correct?
It's not a condition, it's a parameter that you would be sending in those brackets
like what
i think i dont get something
im looking at it like an if statement or something
whats a usecase for this anyway
is it better practice to have a dedicated script for player animations (currently have animation in same script that handles movement) ?
You can skip the variable assignment line above with TryGetComponent.
yes
and then you just use refrences
so in your movement script you refrence the animation script
Otherwise, the if condition is necessary to check if null - null coalescing and nullable likely isn't applicable in this case.
i should make my player states such as (isJumping, isWalking) public in this case then right
in order for it be accessible from the animation script
i dont know how you structure your animation+mobility stuff
i have ```csharp
myAnimator.SetBool("isJump", !isGrounded);
myAnimator.SetBool("isWalking", xInput != 0 ? true : false);
myAnimator.SetBool("isDash", isDashing);
you have to make sure they dont conflict with eachother
sorry wdym by they dont conflict with eachother
since this would be moved from the movement script to the new animation script
maybe there wont be a problem, its just im unaware how its structured
btw
by animation script i understand a script where the animations will call,
that code you dont need to separate in another script
altho it wont hurt if you do
You could make properties for them to be accessed outside your script but not changed, or make events for when those actions start and end so your animation script can just subscribe and effectively update itself, personally I like using events often to mitigate direct references where possible
It's just a short form for writing some code
Also, "is Jump" to me seems like something that would happen by trigger once instead of a ground check bool, but I guess it depends on your setup
can you please throw me a usecase
I did above with the property, and the docs do list quite a few
They really arent that important, which is why u might not see the value in them. It's just short form
mm yea, i've been trying to move away from references too and instead use events. What's the diff between C# events and UnityEvents? I've been using the former
It is effectively storing a function as a variable you can hand to other things for Inversion of Control (IE a callback function the other thing will invoke when it pleases)
You also can do fancy stuff with Lambda Expressions as a mechanism to specify "selectors" for things, but that involves expression tree manipulation which is kind of advanced
If you use Linq you'll get very familiar with lambdas very fast, as you use them extensively
is it used alot in gamedev
would anyone know why lerping doesnt work when i build to iphones
ive seen it being used here and there
and i think its definetly a thing i wuld learn
Unity events can be set from the inspector, and c# events cannot be, afaik, they both use delegates, I personally use actions more often and sometimes setup delegates for specific interactions but nothing wrong with unity events, I use them for physics detection but not much else personally
unity events are more convenient then actions, you just do event.addlistener(function) and thats all
Its a pretty core bit of functionality of C# in general
you don't have to for regular c# events either. it's just common practice to avoid issues
i see, will def learn about them
so if i have an object that subscribed to an event, and it gets destroyed without unsubscribing wont that create a leak
I dunno if C#s garbage collection is smart enough for this, but I typically try and avoid having my monobehaviors subscribe to events at all to avoid this in the first place.
oh yeah speaking of which, does GC happen if there's no ref to the object*, but the object itself is subscribed?
Instead they have some events others subscribe to, but they dont subscribe to any events. They just have exposed mutation methods on them, and their handful of MonoBehavior only events exposed if needed (OnPointerEnter, OnColliderEnter, etc)
if you don't remove it as a listener from the unity event it will likely throw an exception as well
i wuld assume with u nityevents this garbage disposal is taken care of
I actually dislike auto GC. I feel like I need to debug much more to make sure no mem leak
Pretty much yea
It's not really that massive of a deal though in this case, you can avoid it by unsubscribing on destroy or disable
are you sure, if there is no diffrence betwean unityevents and actions aside from the one poping in the inspector, why have both
A unity event is just a serialized event, an event is different from an action
the thing is im not sure unity events have a function dedicated for unsubscribing
Remove listener
An event is different from an action, an event cannot be invoked from outside the class and only exposes the add and remove functions
An action is also just a delegate
im not sure i get it
Theres a pretty good series on all this by jamie king on youtube, hes quite good at explaining
public unityevent variable; is pretty much the same as
public event action variable;
In the context of both of them being events, yea pretty much the same.
Unity event is serialized though and you'll see it in the inspector
yes aside from that
pretty sure you don't want this 
Theres basically no difference otherwise
I mean, we already do GC manually for the scene ;)
if your talking about this guy, his last video is 7 years ago...
A delegate has existed for longer than 7 years
I'm sure if you found a tutorial on how to add 2 numbers from 50 years ago, itd still be relevant today
i get it
Only thing you might be confused on in his tutorials is stuff that's not used in unity like the main function
Which you mightve not seen if you never learned c# outside unity
Jamie actually help me get through a lot of my c# course. It's surprising how much his stuff holds up today for being a decade old
guys actually pretty dumb smart
Got me interested in some open gl stuff too
I like how he pulls up the reflector a lot in the delegate series, it's nice seeing how stuff really compiles
well main is basicly the main loop of the program?
so its basicly like update in monobehavior
Not really, main is just an entry point
It doesnt loop
but it contains all the code from my game right
Unity structure is very different, outside of unity you typically have 1 entry point (main) and then just build everything around that. Unity is different because it already builds so much for you, then just calls a list of functions on monobehaviours everytime they're supposed to happen
Not really sure what you mean by this
main void {
//my game
}
You should probably look at beginner c# tutorials if you're interested in how that part works.. because it's so very different itd take me awhile to even explain
If you follow a tutorial and it has a public static void main, all you have to know is that's the entry point
That is where the code "starts"
ok
Which one do you prefer?
Passing an argument to the base class and set that field into or define an abstract property in the base class and then override it into children classes?
public class State<T> : State where T : MonoBehaviour
{
protected readonly T Character;
public override GameObject Object => Character.gameObject;
public class State<T> : State where T : MonoBehaviour
{
protected readonly T Character;
public State(T character)
{
Character = character;
}:base(Character.gameobject){}
You cant use constructors on MonoBehaviors :x
that's not a monobehaviour though
oh wait thats the restriction on the generic my bad
I misread that, I usually put restrictions on generics on second line
I would go with neither, I would use an interface since there's no actual functionality present in this example for why you need inheritance
What?!
my bad I misread those as MBs not POCOs
neither as I said, Id use an interface instead for what you have there
passing it through ctor or override it with getter
it 100% depends on what you are doing with or need the property Object for
My question is not to change State, use class or interface.
Definitely, it has some functionality that I do not put it here
The question is about this line of code.
public override GameObject Object => Character.gameObject;
or passing it through base ctor
They both seem to do the same thing, no?
but typically, interface is the right call, Inheritence I only use in 2 cases:
-
I have to because I am consuming off some third party class already and thus am pidgeonholed into inheritance from the get-go
-
I intend to serialize the class
Aside from that I always try and use Composition over Inheritance, its easier to debug, fix issues, maintain, and it forces you to keep your code better organized cuz you cant do weird circular Inversion of Control
I think passing it thought ctor is the right one because it is initialized only once and also all children can pass it through easily
The first is easier to maintain, cuz the latter is gonna cause you a lot of hell if you ever change the constructor of State
Yeah, top is cleaner, cause if you gonna have to implement the constructor in the children
But I typically wouldnt use either of those unless I 100% absolutely have to
public class AnyState : State
{
public override GameObject Object { get; }
private readonly List<TransitionStatePair> _states;
public AnyState(GameObject obj)
{
Object = obj;
_states = new List<TransitionStatePair>();
}
so i'm trying to save data between sessions right, and scriptable objects are the best for that from what i've heard (since it lives outside of the scene)
[CreateAssetMenu]
public class BakeMap : ScriptableObject { ... }
so i got this class. cool. but if i try to put it in a monobehaviour class, like this
public class Navigation : MonoBehaviour {
[SerializeField] public BakeMap BakeMap;
...
}```
it doesn't show up in the inspector, at all. I cant set the asset to the ``Navigation`` script on any game object. why is that?
What do you mean it doesn't show up? Have you created an asset from the SO?
scriptable objects are most certainly not suited to saving data between game sessions. they are alright for transferring data between scenes though
this is the SO asset
and this is the navigation script
maybe, but i still wanna learn how scriptable objects work after all
if the field is not appearing in the inspector then you are either using the wrong BakeMap type or you have compile errors. or you forgot to save to let unity compile
Oh, huh. I actually never tried to define without extending out the asset menu attribute. I guess it just makes a single instance in this case? Ah, nm it just flings it into the asset menu at the top level under the class name.
none of these are true
the files are saved, i restarted unity, correct bakemap type
one of them has to be. either that or you are modifying the wrong Navigation class
oh wait, are you using odin inspector or naughty attributes? if not you probably have a custom inspector which is fucking it up. but surely you would know if that is the case already
I'm not sure how to solve this issue. I'm currently using a trigger to wait and register whenever the left mouse button is clicked, which the animation will then play. However, it doesn't finish the animation completely, it goes to the last frame, until I click left mouse button again, and only then will it stop the animation and go back to my walking/idle animation. I've also attached the animator transitions to the both of them, any idea on what I might be missing?
If it's not a problem with your state machine, then you've got exit lag on your animation.
Or rather if you're asking to finish an animation completely, then you want to add or blend it into the next transition.
The video makes it look like you're stuck in the attack animation, or am I incorrect?
yes i am stuck in the attack animation. I’ll click my attack button once, it’ll play the animation but stop on the final frame, then i must click it again if i really want to stop the animation or if i want to attack again. So, if i hypothetically wanted to do 3 attacks in a row, i would have to attack, stop the attack, and attack again
The attack should just be a trigger and its animation should be interupted by walking, and ideally it should play out the animation completely and return to the idle animation when not moving.
yeah that’s what should be happening. i have it set as a trigger, so it should trigger, start the animation, and finish it, but it won’t finish the animation unless i press the trigger again
You can run the animator sidebyside with the scene and it'll show you in real time what state it is in and animation is playing for debugging
if you believe your logic states are correct and animator logic is correct, then it could just be a slider problem for the transitions
(Sorry i think i posted this before in the wrong channel)
but: So I have the basics of C# down, is it just stumbling from random tutorial to random tutorial now?
How did y'all begin figuring this out for yourselves? I don't even know what to start with for a basic feature
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
whats the best way of checking the tag of something below, but not necessarily colliding with a gameObject
i also turned off loop for the animator, but before when it was on, it was just permanently playing the loop until i attacked again. the issue is that the trigger is working as intended. when i use the trigger, it should play the animation once and then go back to the idle animation, however it’s not doing that.
I see, im trying to learn this how I learned a bit of gms2.
oh it looks like there's seperate tutorials on different features on search! Sorry, im new to this engine. Thanks.
Honestly, if you've not really made a game program before, I'd attempt something that's not reliant on frequent updates like board games / chess. From there, people would suggest tutorials on flappy bird (which I actually think is quite a bit more advance with its endless level scroll), but overall, stick with smaller projects with a smaller scope.
gotcha! I've made some games in gamemaker studio but this seems like a different beast altogether. I think im gonna try to make a 2d mario clone which is what i was working on in gms2
Yeah, that sounds ideal, and there's probably a ton of tutorials out there for that in unity
Does it show in the animator that it's transitioning into walk when you're moving after attacking?
Only after the second attack, here.
It holds that animation, even though it's a trigger. I have no idea why it's happening.
look at the transition condition
Can you elaborate? this is like my second day of using unity lol
you literally have it highlighted through the entire video. the condition to transition out of the animation back to your idle animation is that the swordAttack parameter has to be triggered
Pretty cool. Reminds me of the gba dragonball z games
oh that's a little awkward haha, thank you for the help! it's always the easiest things that mess me up
Mostly just need to double check what the conditions (if any) are on the Attack > Idle transition
perfect thank you! There's also like a teeny tiny bit of delay from when I click left mouse button to when the attack actually starts, I've tried to change the speed of the attack and everything, but it just doesn't change that like wind up time. Is there any way to fix this as well?
it feels as if my character has high ping
yeah you need to set exit time on idle to be zero prolly
I wish there was a specific 2d Animator that removed a lot of this stuff and worked for sprite animations better
Cuz pretty much always you want exit time to be zero and whatnot for most sprite things, because we dont have any kind of blending on em needed
I figured out the issue but I don't know how to solve the issue. The attack animation must wait for the idle animation to be complete first, so if I click attack at the start of the idle animation, I must wait for the idle animation to finish, then run the attack animation. Do you know how that might be able to be solved?
yeh its one of the values on the transition itself, one sec here
Transition Duration I believe needs to be zero
and Has Exit Time should be false
On whatever your transition into Idle is
perfect, you're a life saver
I wonder if someone has made an animator that is better suited for 2d sprite stuff
like as an example, the Mirror property on Animator doesnt work for sprites, would be nice if the 2d version actually worked for it instead of needing to manually add custom code to handle flipping the sprite.
Its easy to do but still extra effort a custom animator could've handled for us
Hi, I wanted to ask a bit of a higher level question on how I should code something. My game allows the player object to go invisible, and when the player object is invisible, I want the player themselves to be able to see their sprite at like .5 alpha, but for other players to not be able to see the object at all. I was thinking about how to do this with layers and camera culling, but I'm not sure how to do it.
I'm using Fish Networking if that's of importance
it definitely is frustrating, I used to mess around in godot a little before this and even their animating stuff just seemed simpler than this. Of course godot is much more beginner-friendly, and unity can do much more complicated tasks, but it was still a definite learning curve
Havent used fish personally so cant really provide specific examples but you would simply have the server send out some event to all clients saying to set it to 0, except if you're the owner then set it to 0.5.
By some rpc
damn that does make sense, I was misled so I've been trying to figure out a way to do it with two different cameras and culling masks
realizing that doesn't make sense now
I'm sure you could but directly changing the material might just be easier
Hell it even be easier to just straight up disable the visuals for other people lol
For sure, thanks for the help! I also asked on the Fishnet server and they recommended looking into a custom observer condition because it would be hack-proof while rpcs wouldn't be. I'll look into both and see which one works best for me though, appreciate the help 👍
What I suggested definitely isnt completely safe, but nothing would stop a client from drawing their own visuals by having the game objects location. You should consider if you even have to worry about hackers
True but they said that with a custom observer condition they wouldn't even have position updates
which also might be more performant
in my game im just saying fuck it, people can only play with steam friends. If you wanna hack then you just ruin/boost your friends experience
I havent really heard of that tbh
https://fish-networking.gitbook.io/docs/manual/guides/observers/custom-conditions it seems like it's fishnet specific
Ah I think I understand, that does seem pretty useful for your case actually
In the revolver prefab's inspector window, the inspector window is not allowing me to assign values to the revolver's Firearm script. How do I fix this?
currently using unity's tilemap system to make level design more efficient, however i can't seem to figure out how to add functionality to each tile (eg. destroy a tile when that specific tile collides with a player). Is there a way to accomplish this or do I just have to suck it up and make prefabs for the tiles that I want to have functionality
which values are you trying to assign?
how can compare a value to more than one enum value? instead of doing something like this:
if(Value != BlockType.Air || Value != BlockType.Water){}
So umm i was working on my project and suddenly my camera scene view flipped and now the camera controls in the scene view are inverted (move mouse left and camera goes right) Helppp\ (image is being viewed from below Pov)
Blargh, I think rider's auto fix stuff borked the files in the auto generated cs projs...
Anyone know if theres a quick way to fix this? Do I just delete the .csproj files and regenerate them?
u can rotate scen camera in all degrees of vision, there are no constraints, try flipping your camera the right way up.
how
its in scene
right-click and drag
if you're on 2021+ you can use the is operator like Value is not (BlockType.Air or BlockType.Water)
is "is not" equivelent to != in these worded functions are is there some caveat?
it's for pattern matching, but yes in this case it means literally what it says. much like != means not equal to, is not means literally is not
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/is
in this case you're just matching it against a constant pattern
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/patterns#constant-pattern
c# just keeps getting more complicated man, Thanks for the help!
btw you would want to switch to and instead of or for the same logic as the if statement in your question. although if(true) works exactly the same because it cannot be equal to both at the same time so one of those conditions has to be true 😉
of course if this is for enum flags rather than just storing one value of the enum in a variable you have to do things differently
is there a way to bake and store navmesh data in code?
did you google it?
It's not at runtime it's code executed in editor
yea either it said no or it was BuildNavMesh() which doesn't store
are you using the AI Navigation package or are you in an earlier version?
no I'm using LTS and default unity navigation
by LTS do you actually mean the 2021 LTS? because the 2022 one uses the ai navigation package
2022
otherwise the BuildNavMesh method should work. unless you've been trying it in play mode and expecting it to persist once you leave play mode
no I'm using it in editor. I'll try this now
yea this works thank you
if you are not using it while Play Mode in the editor is active then BuildNavMesh should work
it does create it but then when I go into play mode it disappears. the NavMeshAssetManager works tho
For some reason this is happening to my project. I have not done anything to it for a long time and I am using the same version of unity to open the project and it worked the last time I used it. Now after transfering to a new computer, this opens up every time I open the project. It does not prevent me from being able to run the game though. Thoughts?
How can I spawn something in front of the player, at certain distance, but have the distance between the player and spawned object be the same, no matter the object's size?
you can increase the distance based on the extents of the object's renderer bounds
it is not a perfect solution though, since bounds are a bounding box and not a bounding circle, and various factors could make it be a bit inaccurate
a more perfect solution would be to create a custom offset per object (via the inspector + a gizmo for visualizing)
but that is not automatic
even a custom offset that you set in the inspector would fail when it comes to rotations
realistically the bounds should just be fine
Hi, trying to decide between two designs, would like to know if there are any ideas of which one is better or if there's an even better alternative:
- creating an "attack" gameObject as a child of player every time the player performs an attack, which then destroys itself when the attack ends
- Have an "attack" gameObject created on Awake, which is always there, and creates/destroys components when the player performs an attack
Thanks.
What kind of "attacks" are these? Do they have to be game objects to execute?
Basically the attack needs to generate hitboxes of certain size/position on specific frames, like a fighting game. They don't have to be in a gameObject, I think the colliders/rigidBodies could also just be components of the player, but I felt like it would be better if there was some separation
and so at any given time, the player can only be executing one attack, which must conclude before they can perform another one
Ah, if they were just colliders, you could use casting from a vector so you wouldnt need to instantiate/destroy, if you have other components you need, maybe you could try to pool generic attacks and change the values and visuals when you pull from the pool (one way is with ScriptableObjects, another could be your component approach), if only 1 attack can ever be active at once, a state machine for your attacks sounds like it could be a good idea, but those dont technically have to be mono's, though there may be other approaches you could take, the idea of having to constantly instantiate/destroy objects or components seems like it could be taxing on performance
I see. Would enabling/disabling the components be better performance wise?
like when the player attacks, set the positions of the hitboxes and enable those components, then disable them after
Im not completely sure actually, I know that toggling child game objects have a performance hit depending on how many child objects there are (for example, if you had a parent with 12 child objects and you toggle the 10th child, the other 11 get set dirty and calculated the next frame even though they didnt change), not sure if that also applies for components, but that also means if you have say 200 attacks in your game, you have an object with 200 components, which youd probably want a reference to each so you dont have to GetComponent search every attack
I'm thinking each attack would only have 1-5ish hitboxes, and the frame data for the attacks would be stored in an array. So depending on which attack is executed, grab the attack object from the array and read the info from that, and manipulate the 1-5 colliders/rigidbodies accordingly.
So, if it's for getting collisions only (and the timing could be handled separately), then have you considered overlapsphere/circle/box etc with the center positions where the attack is supposed to hit?
Oh wait. Did you mean being HIT in different spots causes different damage/effects?
hmm I think this could work. The only problem is I want to make sure the movement of the hitboxes is interpolated between frames (not sure if I'm saying that correctly). Although I suppose that could be achieved with using overlapCapsule() for when the hitbox moves from point A to point B in a frame?
(from melee) this is basically what I'm trying to implement
and yeah ideally, depending on which of those red circles contacts the "enemy", it could have different effects
Not sure what you mean. You could call 3 overlaps on frame 10, then X on frame 11 at the different points, each handled differently.
Not sure if that's more or less performant than enabling/disabling children though. I would assume it is better than instantiating and destroying though
I mean like in the picture, how frame 10 of marth's attack has circular hitboxes, but on frame 11, they are capsule shaped, because it is connecting the circle from frame 10 to a new circle. So this prevents something from "slipping through" the attack between frames
Oh, it looked like a bunch of interlocking circles. But yeah, you can do capsule too
Yeah thanks. I think I'll try with the overlap methods, as it feels cleaner than creating/destroying or enable/disabling things. I think the performance probably isn't a concern for my game
When in doubt, theres always the Profiler to confirm how your solution ends up performing
oh thanks, I'll have to look into that at some point
I'm trying to assign all the values
Why is the name of the prefab variant greyed out?
I'm wondering whether that could have something to do with it.
So, I'm assuming you didnt find a fix?
just have a collider that fits the entire weapon and do a raycast or overlap as suggested. you do not need to create those extra circles (objects) on frame 11. the collider(s) from frame 10 would catch the collision on frame 11 . . .
also, enabling/disabling a component is better than constantly activating/deactivating a GameObject . . .
does anyone know how to make a nav mesh for 2d tile map or at least 2d. I have static tile map. I add nav mesh modifier to each of the children in the grid with walkable and non-walkable areas. And I have nav surface as parent and I bake with appropriate settings but it fill the nav data with anything.
nvm
unity's navmesh does not work in 2d by default. you need an asset like NavMeshPlus or some other pathfinding asset
Quick Question: Unity player setting has a option in Resolution and presentation by name "Render over native UI". I need this setting to be turned for a specific need; but as sson as i turn it on; any image /font or any game component that has alpha lesser tha 255; will start displaying actual screen of the operating system;
Quick Question: Is there anyway, to spawn in predefined 2D structures on a tilemap?
how do i make an object rotate toward the player
That's something you can google
Just add 2d or 3d, or if on any particular axis if necessary
Then you should provide more details on what exactly you're looking for
People here only know as much context as you can explain
well im just making homing projectiles in my game and transform.lookat isn't very dodgeable so i need the projectile to rotate toward the player at a set speed
Look up how to make homing projectile unity
is objectively better to use the new input system with the Player input component and not the C# script?
Because usingLookAt is instant. You need to get the direction to the player and manually rotate to that direction based on speed or time. You can tweak either of those values to have a more or less responsive missile . . .
Rip, lol . . .
i got a pretty simple homing code
what's the best approach for making an AI that roams by default, then if it is attacked or spots a player moves towards them, and if it is within X range of the player performs an attack animation? I'm currently using a FSM via interfaces but running into problems with script referencing.
{
IState currentState;
public RoamState roamState = new();
public ChaseState chaseState = new();
public AttackState attackState = new();
private MovePositionPathfinding pathfinding;
private GameObject player;
private void Awake()
{
pathfinding = GetComponent<MovePositionPathfinding>();
player = GameObject.FindWithTag("Player");
}
private void Start()
{
ChangeState(roamState);
}
void Update()
{
if (currentState != null)
{
currentState.UpdateState(this, player.transform.position);
}
}
public void ChangeState(IState newState)
{
if (currentState != null)
{
currentState.OnExit(this);
}
currentState = newState;
currentState.OnEnter(this, pathfinding);
}
public void TriggerOnHurt()
{
currentState.OnHurt(this);
}
}
As you can see the statecontroller passes in the required data to carry out state logic in the UpdateState and OnEnter functions
the problem is, as the number of states increases, I am passing in more and more data through these functions which is messy
I cannot retrieve the data from the states themselves, as these aren't monobehaviours and just belong to IState
This is my first time making an AI and it feels messy. It seems like this approach would be fine if the states were very simple and did not require external data for their logic.
use either an enum or strings (Documented Well) for states, maybe define some triggers as functions if youre using ScriptableObjects paired with UnityEvents or use an abstract inheritance class Called AI if each enemy has a script
i wanna know if theres a way to add TTS?
whats tts
text to speech
most likely
you know how?
Have you looked it up?
How are these two different?
public int someInt = 3;
and
public int someInt;
void Awake() {
someInt = 3;
}
thanks
- Its initialised with 3 to start with when you create the object.
- Its only set to 3 when the object has Awake called on it, otherwise someInt is 0 up to that point (or whatever value set in inspector view in Unity)
oh thanks!
If that code is in a Monobehaviour. in the first example the value of someInt will be 3 when the component is first added to a gameobject thereafter the value in the inspector will take precedence.
In the second example the value set in the inspector will be ignored and someInt will always start at 3
Thank you :)
lads how do i get a script from an object without knowing the name of the script?
Like I am trying to refine my shooting mechanic by adding different bullet scripts that fire differently
and all of them have a Fire() function i just need to call it
Use inheritance or interfaces
wont the inheritance access the inherited script instead?
like if i do
GetComponent<Bullet>().Fire()
~```
wont it call the fire function in the `Bullet` script ?
It will call the overridden functions if you have overridden them properly with the override keyword
ohhhh that makes sense
thanks vertx
Hey guys this is kinda hard to explain but is there something that will act as any number
here is what I want to do
if (assetNames[j].Contains("("))
{
assetNames[j] = assetNames[j].Replace($" ({anyNumber})", "");
}
Does this make sense?
Basically if i have 3 objects named
Box (1)
Capsule (4)
Tree (9)
I want the name of that object to be saved as
Box
Capsule
Tree
no
i think you need regex
Hmm I am unfamiliar with that
it converts a boolean into a number, if the forward is pressed the value is 1 if backwards it -1, if both its 0, cancels out
which allows you to write a single mathematical expression to handle it instead of large if/else tree
https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.replace?view=net-7.0
you can use this. regex is just a way to match for patterns in strings
I like this site for testing regex quickly https://regex101.com/
asset names? are you working with asset database?
you can use AssetDatabase.GenerateUniqueAssetPath which does what you want
sort of, without brackets
im wrong, misunderstood
Its an array of game objects that is created when I search through a tag called "Savable"
without regex the simplest is to get LastIndexOf(')')
from there find the opening bracket, and get a new string with Substring
problem is that when an object is duplicated it adds the (x) to the end of it in the hierarchy
duplicated how?
you are instantiated already spawned object? cloning it?
or from prefab? if from prefab just use prefab name
It is a prefab but by clicking on an object in a scene and selecting "duplicate" it will make that object + (x) at the end of the name
when make the array of those objects it includes that (x) and it messes with something I do later that needs just the prefab name
/// <summary>
/// Assumes the object may have (n) as postfix
/// </summary>
/// <returns></returns>
string GetNameWithoutNumber(string name)
{
int closeIndex = name.LastIndexOf(')');
if (closeIndex != -1)
{
int openIndex = name.LastIndexOf('(');
if(openIndex != -1)
{
return name.Substring(0, openIndex);
}
}
}```
may need -1 in substring
do you mean in place of the 0?
no
openIndex may end up exactly on (
so you just offset by 1 in case that happens
also trim it
return name.Substring(0, openIndex).Trim();
you would also have to return the original string if it doesnt exist
I really would just go with regex, though it may look kinda messy since you'd have to do escape sequences on the brackets lol
*\(\d*\) would capture any amount of spaces followed by (, followed by any number, followed by )
I already dealt with the (Clone) thing
regex is like rocket science to me, i could, but id rather not
in most cases regex is honestly really easy
Same haha I have 0 experience with it
for some reason even though this is returning a string unity is acting like it isnt
your case for this is like one of the things you learn when starting out. You may just have to add extra escape sequences because c# doesnt like \( so it might have to be \\(
its easy when you get into it, understand its fundamentals, learn the tokens and what they mean, work with it for a while
not saying you shouldnt do, im saying you have to commit
and who has time for that
Nvm i realized the problem with the returning thing
i never get into the actual hard regex, like when i see something online suggest a lookahead I just find a different solution 😆
fair
Ill look into regex if this does solve what im trying
it does solve it, and u can also have it handle the (clone) at the same time
The (clone) shouldnt be an issue but thats good to know
the only reason this is an issue is because its not at runtime so I cant fix it when the objects get instantiated
blue means it matched, green means a subset was detected so dont worry about that part
it does look a little chaotic, but purely because its trying to match for () which are tokens already in regex. So we need to escape each with \
and then i have another pair of brackets and a | to say match (number or "clone")
it does get somewhat confusing when you try to match a lot at once, but itd be the same case writing it all out with pure c# strings
theres just a regex.replace function
the one i linked here, you detect a regex then replace it with ""
ohh gotcha
in here, what is Constants.Horizontal?
thank you Ill see if i can figure it out!
Assuming it's some class in another part of the project which defines input axes
alright goodluck, i expect you'll probably have to deal with the escape sequence thing i mentioned so if the regex i wrote doesnt directly work just put \\ for every \ i had.
okay can do thank you
hey, anyone know why the random position mover dosen't show up in the events tab?
RandomPositionMover does not have any public members, therefore there is nothing you can modify with a unityevent
Nevermind, float values, forgor
Uh, maybe not all of the objects you have selected have a RandomPositionMover component?
they all have the same component and the same configs, i have tried restarting the editor but it dosent seem like anything works. i even talked to chatgpt and not even gpt could give me an anwser
nvm i fixed it!
How can I spawn something in front of the player, at certain distance, but have the distance between the player and spawned object be the same, no matter the object's size?
(this code can even make the object spawn on the player if object too big)
you will need to get the object bounds for that
Find a way to get the size of your object, and add that to the distance
which is an annoying task
all the objects you spawn have colliders?
you can use both Renderer and Collider bounds
Also think bout your current use-case, does it make sense to have it float of the player hre? Spawn building sounds like a building system, wouldn't you want to raycast to the terrain to place it on the terrain instead?
the algoright goes like this:
collect all Renderers and Colliders in the object
cache object rotation
set object rotation to zero
declare new Bounds
loop through all colliders and renderers, doing bounds.Encapsulate
set rotation back to original
use the new bounds to determine objects "size"
this will give you approximate total bounds of the object, which you can then use to get an approximate distance the object should be offset by
Okay, I think something like that:
My use case is simple but for complex object would have to do what you said above
how can I build a hashtable that's modifiable from within the class, exposed to other classes but not modifiable by them, and where I don't have to duplicate the collection into a readonly collection every time other classes attempt to access it?
Expose it as https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ireadonlydictionary-2?view=net-7.0
E.g.
public IReadOnlyDictionary<K,V> Example => myDictionary;```
Also if it's not clear you should use Dictionary not HashTable
So this does not create a new dict/generate garbage?
very cool, thanks
How can I calculate the distance between the player and an object, but from the object's bound rather than it's center point?
(this is what i have that's better than not taking into account the building's size at all but it's still far from perfect)
i could probably just raycast but was wondering if anyone knew the 'maths/physics' approach
raycasting is the maths/physics approach
Hihgly recommend using this: https://docs.unity3d.com/ScriptReference/Collider.Raycast.html
rather than a general physics raycast
so equivalent to getting both of the objects bounds and calculating the distance between?
not at all no
that's what i was infering above, sorry was pretty unclear
you would need to do two raycasts
one against each object's collider from the other object's position
to get the two "edge" points
then check the distance between them
hmm, what i meant is, through code, so with the world position of the objects and the bounds, something like that could be achieved
but my head kinda hurts thinking about it so i'll just go for the single raycast approach which seems to make the most sense
- Bounds are not necessarily a good indicator of the edge of an object anyway. A well shaped collider is much better
- you would just be rewriting the box/ray intersection that BoxCollider.Raycast does anyway
thanks!
hey can someone review my code? its a item shop script for a vr game but it crashes my unity if i try to start the buying process, would be really nice becasue i ran out of options why its crashing and i dont know if its unity or my script whatever heres the pasty link if you want to have a look at it https://paste.myst.rs/c61jnzsh
a powerful website for storing and sharing text and code snippets. completely free and open source.
You most likely have an infinity loop.
just as a suggestion, learn how to use the code debugger
That would be: while(isslecting)
hm i see
You gotta use a coroutine if you want to use this approach.
oh oke i though i could use a loop like the update method and break it if the player is done selecting
You cannot use a while(true) loop.
oh ok thx for teh help
📃 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.
do i need to replace all loops
First, follow a tutorial on what are coroutine and how to use them.
ok it worked
layers are confusing... once i add a masking layer to raycast, it wont detect anything, no matter what layer it is in.
you must have done so incorrectly
layermasks are simple - the raycast will only hit colliders that are on the layers in the mask
that's it
code
Debug.Log("HIT!");
return true;
}```
script in parent, there are 4 childs with collision in it.
it should only detect one of the three collisions in camera.
LayerMask.NameToLayer("lyr_blocks") is not correct
but... LayerMasks are bitmasks, not simply Layer Ids
use LayerMask.GetMask("lyr_blocks")
ah i see
Hello how can I make Physics.RaycastAll follow correct order ? only LINQ?
what does "correct order" mean?
sorting
closest element is always 1st
then sort it
I can use OrderBy?
What do you need the ordering for? There may be a better way to achieve what you want
nobody is going to stop you
I want to have the closest be first detection
that's a truism
but WHY
what's the goal here
each my box has a random number, I want to detect total number but closest first
can i put like 3 or more of the same collider type in a single gameobject and have them all pertain to a different behavior? like, a player having colliders on their sides so they stop at walls, but not to stop their fall if they're falling next to a wall (and in the same way, to not stop their running side to side when grounded at the bottom collider)
oh wait, is there such a thing as Collision2D telling you which collider got contacted?
it does have a collider field and a list of contacts if that's what you mean?
oh i found something called GetContacts
i wonder how that works
ContactPoint2D
it shows the actual position of contact
i could use this
yeah, definitely!
that's why Unity wrote documentation, so you could read it and learn
3d text mesh pro is always facing the camera. is there a way to disable it?
it is not always facing the camera 🤔
it faces wherever you tell it to face
no for me it is
you've done something strange then
show your hierarchy and the inspectors etc
strange... it's not doing that for me
ik it shouldnt do it unless done by code or contrant
ive googled and found out about billboard but i dont have it. its a new project
try a fresh scene?
maybe something in your scene is doing it
do you have "Orthographic mode" turned on for the TMPs?
no
what was the issue?
i removed all the contrants and it works now
ah
will figure ouyt which one was the problem and solve it
fixed it. script problem. thanks
I never see you initialize the BotRends list. You are using the .Add method on the list which isnt initialized yet. In other words, you are trying to call a method on a null object, hence the nullref exception.
Ok thank you I will check that. Out of curiosity, why does it work sometimes and the other times why does it work on the first element if that is true?
this will not do what you think it will
you are accessing .material which means you get a clone of the sharedMaterial
so reset in this case assigns the new clone back the new clone
you are also calling .material on each submesh, meaning you are creating a clone for each of them
instead you should not access material at all, and instead use either MaterialPropertyBlock, or CommandBuffer to draw the flash
Thank you @slow trout that seems to have solved the issue
I will look into the MaterialPropertyBlock thank you
first means you wont create clones but it needs a shader that flashes, second will simply draw same mesh with flash material on top of existing one without creating any additional scene overhead
Good. And that is using the Propertyblock?
first - block, second - command buffer
So both should be used?
one or another
they both solve a problem, in different ways, but both are more efficient than .material
Ok, thank you for your help/time
It is now that I changed it
its for me
private List<Renderer> botRends = new List<Renderer>();
private List<Material> baseMats = new List<Material>();
so far the only case when i know things like these happen is with statics
it is unclear to me why did it even work the first time
No statics here
what code could potentially initialize it on first play, and not on second
Disable Domain Reload option
My thought exactly
domain reload wont initialize the list the first time
Tried that, no effect. Had a similar issue with another script, its off
Just had a similar problem in Editor (i.e. not in Play mode)
im asking why did it work the first play session, unclear
I am
then dont listen to me and ask in #archived-urp what is the best way to solve such cases, they changed too much for the old approaches to be applicable
what you really want to know is how urp handles .materal and lots of dynamic material changes
it doesnt behave the same way, im sure it still copies material, but im not sure it has the same performance impact as on built in
back again. is it possible to set the origin (for rotation) in script?
objects will always rotate around their pivot
the pivot is just... the position of the object
pivot is something that doesnt actually exist, kinda
Do you perhaps need help with rotating an object when it's already rotated?
Better off describing your problem rather than your attempted solution
What's it currently doing?
its a thread now
let me give you a hint.
I guess this is 2D Tetris.
make a 2D array for each shape with an offest to the actual pivot point, then you can rotate relative to that
yes.
gotta implement wall kicks though too ;)
I think that feature is more relative to the newer tetris games though?
Split it into multiple frames with a coroutine
Could someone help me with my spawner script🙏🙏
You may need to provide some more info - what issues are you having or struggling to understand, and what have you tried so far? And what is it your trying to spawn?
So I’m making a wave shooter and I’m trying to spawn enemies at random points on the map, but if I just use random range it puts them in obstacles and walls that are on the ground, so now I’m trying to make it so they can only spawn on random points on their navmesh but can not figure out how
I can send an image of the code if that makes it easier
No screenshots. !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.
No DMs either. Post the code here as per the instructions
No ones gonna dm you to help you for free. That's just tutoring
I mean it’s probably just a quick fix with the script
I don’t know if I’d call that tutoring
Rules say to keep all the questions here, see #854851968446365696 at the top
I need this fix so bad man I’ve been staring at a couple lines for hours
Would u rather fail to convince someone to tutor for free, or just post your question like a normal person
Oh
Once again, #854851968446365696, the least read channel lol
Bro that’s what im doing
I asked if anyone could help then someone said provide more details and I did
We also asked you to post the code and you didn't
Again, #854851968446365696 has all the instructions listed on how to post a good question
Yeah but it’s on my computer and a picture would be a lot easier
If I could just post the picture of my computer and someone could look at it and tell me the problem I’d be very thankful
Discord can run on a browser, don't go and take phone pictures of screens
For you sure, but not for us
This guy did it and it worked for him
Honestly you couldve just googled this issue instead of arguing like a psycho so you could post your code in a shitty way
Literally "random point on a navmesh"
Try harder, or try harder to read the read me. This is a waste of time
Trust me using discord is the last thing I’d want
yes
yes its gone
Great another screenshot of code
Literally top ten most readable things I’ve seen today
Heya, I'm using this code in a GameObject's monobehaviour to make it snap to a 2d grid,
{
this.grid = transform.parent.GetComponent<Grid>();
this.gridscale = transform.parent.localScale.x;
//snap to grid
transform.position = new Vector3(Mathf.Round(transform.position.x / this.gridscale) * this.gridscale,
Mathf.Round(transform.position.y / this.gridscale) * this.gridscale,
transform.position.z);
}```
However, it snaps it to the point exactly in-between cells. The transform x and y values are correct on the GameObject, so I assume it has to do with the tilemap's Tile Anchor-value. However, if I set the anchor value to 0, it seems to mess with other stuff I have that uses the WorldToCell / ScreenToWorldPoint functions. I could just add `0.5*gridsize`to the x and y, but I'm worried this will cause other issues down the line. Is there a "recommended", robust or just better way to get gameobjects to snap to a grid?
Fine man I’ll try to find somewhere else that can help
Good luck
Thanks man you were actually civil unlike my man bawsi throwing around words like psycho
Are you trying to make it go to the middle of the grid tile? Just adding half the size should be fine in that case
The behaviour described seems like it's doing what you want so im just trying to clarify
Yeah, its sprite is the size of a tile, so I essentially just want it to fit directly on the tile like a chess piece or something like that
Offsetting it should be fine, as long as your future code is aware of this when you check the position. You could maybe even separate the visuals so that the gameobject exists at the current location you have and the visuals are offset
I was thinking about something like this, but the Sprite Renderer component on the GameObject doesn't seem to have an anchor or anything like that to fiddle with to make it draw from the corner point. I'll implement the offset - thanks for the input
Question: If I setup a variable to be a lambda of a function, is that like the same as setting it consistantly in the Update Method or no?
public int AttackDamage => SetAttackDamage();
vs
public int AttackDamage { get; private set; }
private void Update()
{
AttackDamage = SetAttackDamage();
}
private int SetAttackDamage() {...}
"If I setup a variable to be a lambda of a function"
This is not what you are doing here.
You are creating a property called AttackDamage which calls the SetAttackDamage function when you read it
it's the same as
public int AttackDamage {
get {
return SetAttackDamage();
}
}```
Your AttackDamage is also just a getter in the first one
Doing AttackDamage = SetAttackDamage(); in Update is definitely not a good idea
for many reasons
also this "SetAttackDamage" function seems poorly named
it seems to be retrieving something, rather than setting something
I was thinking about having an Event be called when anything is changed that will make the Damage change.
It's unclear what the event would be needed for
it's also unclear what SetAttackDamage does
private int SetAttackDamage()
{
// Weapon Dmg, AttributeValue
// Dmg = MainAttribute * 4 + SecondaryAttribute
try
{
Player player = _character != null ? (Player)_character : GetComponent<Player>();
if (player != null || player.JobSystem.CurrentJob != null)
{
int main = 0;
int secondary = 0;
List<Attribute> attributes = new List<Attribute>()
{ ((Player)_character).Stats.TotalStrength, ((Player)_character).Stats.TotalDexterity, ((Player)_character).Stats.TotalIntelligence, ((Player)_character).Stats.TotalLuck };
main = attributes.Find(x => x.AttributeType == player.JobSystem.CurrentJob.MainAttribute).Value;
secondary = attributes.Find(x => x.AttributeType == player.JobSystem.CurrentJob.SecondaryAttribute)
.Value;
attributes.Clear();
float weaponMultiplier = 1.2f;
int attValue = main * 4 + secondary;
int damage = Mathf.RoundToInt(weaponMultiplier * attValue);
return main > 0 ? damage : 0;
}
}
catch
{
return 0;
}
return 0;
}
kind of sounds like you have some function for calculating attack damage which is non trivial and you'd like to cache it?
Essentially sets the Damage value based on the characters Attributes. Later it will factor in weapon equipped and so on
I would do this:
bool dirty = false;
int _cachedDmg = 0;
public int AttackDamage {
get {
if (dirty) {
cachedDmg = CalculateAttackDamage();
dirty = false;
}
return cachedDmg;
}
}```
whenever anything happens that would change the value you can set dirty = true
you could do that part through events if you want
for exmaple this could be listening to events on the player like "OnEquipmentEquipped" or something
So equip new weapon, Event triggers , sets dirty to true, then get AttackDamage
yea
and otherwise the calls to AttackDamage will be fast since dirty will be false
we will only return the cached value
So what you are saying is happening right now tho, is that every time AttackDamage is being called, its always running that Function?
well I don't know what your code looks like right now
If it was this:
private void Update()
{
AttackDamage = SetAttackDamage();
}
``` then you're running the funciton every frame
which is also wasteful
the lambda
with the lambda the funciton will run every time you access AttackDamage yes
so both of your examples are running the function way more than necessary
Gotcha, makes sense. So as you suggested, caching the most recent value so it wont have to run over and over.
i have a problem, whenever i try to build an APK for my mobile game this error shows up and i get 4 long error it the console and i dont know how to fix it
well obviously reading the console errors is the first step
i dont understand them or how to fix them
@leaden ice Thanks a lot! Going to implement this now!
I'm thinking about logically how I want to handle a process where I have multiple "rounds" worth of player actions queued up, but there is an automatic trigger for the player attacking an enemy they are facing.
So there can potentially be both a "pre-round" and "post round" free attack if they both start off facing an enemy and end facing an enemy, plus a movement in between the two.
I pre-calc all rounds worth of actions and then hand them off as a sort of animation+movement queue they all individually work through.
The tricky part is keeping them all time synced, so I need to track how long the round is for the "slowest" entity (due to animation time), and slow everyone else down to keep pace
As an example if I have 3 enemies, 2 just walk 1 tile, third has a 1s long ability it performs, I want the other 2 to walk a bit slower and pause at their tiles for a total time of 1s so everyone "finishes" the round in sync @-@;
Where is the issue ? You just explained your solution and it seem valid.
I think I need to:
Step 0: allocate a dictionary of everyone's actions they will potentially do
Step 1: calculate all the moves for round n
Step 2: calculate the longest entity's move for round n
Step 3: save this set of moves + time to aforementioned dictionary
Step 4: n+1, back to Step 2 til all rounds calc'd
Hey I am making a top down shooter which will have multiple different guns, so I for simplicity's sake I have an abstract class for all guns that handles the general logic for all of 'em, problem is it seems I cannot use the Awake() method in both the abstract and the specific class meaning I cannot set general parameters and use Awake() for more per gun uses, is there any way to circumvent this or am I aproaching this completely wrong
Yes you can use Awake in both.
The tricky part I'm thinking about is unlike other entities, the player can do 1 to 3 moves in a single round, due to the "pre" and "post" attacks, and figuring out how I math out the "time" for that
protected override void Awake(){
base.Awake();
}
Cause I ideally want to make her run faster between 2 tiles if she had an attack, and even faster if 2
hmm so I put that in the specific class and it will run the more general stuff aswell?
But she may also stay stationary and just attack twice without moving @-@;
You just need to calculate all the action that will be done don't you ?
Is it a turn by turn or not ?
Nah I need to change the timings to "squish" actions to compress em
The "attacks" are free and don't use the turn, they occur automatically when conditions are met, but have animation time