#💻┃code-beginner
1 messages · Page 578 of 1
So this is an error waiting to happen
it always stays under .count so it should be ok
It’s removing elements mid loop, it could try to remove at -1, it’s not ok
if the script pretty much does the unintended thats a diff story
Ahhhh, that’s unintuitive
--i returns i - 1 and subtracts
oh that's cool. Is there a place where I can read about it? I don't know how to come up with a keyword for it.
yeah sorry never seen that before lol
hmm I should learn to make C# project so I could test code without waiting for unity to load
smort
You can also use something like dotnetfiddle.net
use C# console apps, they are fast
or yea online compiler is good enough but very basic IDE
I assume enemies.Count is updated each loop then in the condition, so it stays within new limits without indexing something not there
It would generally be better to use a reverse for loop
As then you don't have to do anything special with the indices
You can write them easily by autocompleting forr
I’m very python minded so this entire situation hurts my soul
ya that code caught me offguard lol
Removing from the end of a list is cheaper than the front, so it'll be more performant too
also only for loop can do this, foreach loop cannot because the collection becomes Immutable
(you get met with error in trying to do so)
Why would that be faster? If it’s removing at the index wouldn’t it be the same speed cause you are providing the exact point
all elements after get "moved" up
Ahhhh
so removing from the end first ends up being quicker
Ok makes sense
yikes I thought they'd just move the pointer to the second element
What pointer?
If you remove the second element then there'd be a gap in the array. It needs to be continuous
I am looking up a variable from an instantiated prefab to an object in scene.
The variable changes but I can only ever get the initial value, even if I find the object and component in Update().
Why?
not a code question. #🖱️┃input-system
probably because you misunderstand how value types work
Presumably you're not looking at the objects you think you are
you might be referencing the prefab not the object you created
but I'm getting the value initially, just not when it changes
show code
I'm finding FROM the prefab an object in the scene, so it shouldn't be an issue
spawner = GameObject.Find("Spawn Manager");
spawnManager = spawner.GetComponent<SpawnManagerX>();
// Set enemy direction towards player goal and move there
Vector3 lookDirection = (playerGoal.transform.position - transform.position).normalized;
enemyRb.AddForce(lookDirection * spawnManager.enemySpeed * Time.deltaTime);
this is what I moved to update
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
{SerializeField] GameObject p_bullet;
void Start() {
var bullet = Instantiate(p_bullet);
}
p_bullet gives the initial value.
bullet gives current value
sorry for formatting, I will learn
enemySpeed is the float that I can only get the initial value of even though I moved it to update
you may also have 2 spawn managers in your scene
nope
this is a problem with using GameObject.Find, it may pick the wrong spawnmanager
and you tested that Update is running with logs?
you'll need to learn how to debug your code, and check that you're referencing the correct spawn manager.
and which value are we looking
this is hella wrong * Time.deltaTime
you don't use that inside AddForce
that will make your rigidbody crawl without boosting its speed to ridiculous numbers
we are looking at enemySPeed
AddForce already takes into account (Time.fixedDeltaTime)
physics steps is already fixed time
since I don't know how to format 😄
You need not include it in
then learn how
screenshots are not friendly to people who use screenreaders or blind :\
or to copy/paste solutions
Ok I will sorry
I am proficient in playmaker and can make a game fully without help, but code still confuses me
I am learning
Debug.Log($" enemySpeed: {spawnManager.enemyspeed} ");
what has that to do with following simple bot instructions? !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Wasn't a reference to formatting, just this code problem
Ok one sec
When I add that, I get this error:
Error CS1061 'SpawnManagerX' does not contain a definition for 'enemyspeed' and no accessible extension method 'enemyspeed' accepting a first argument of type 'SpawnManagerX' could be found (are you missing a using directive or an assembly reference?) Assembly-CSharp C:\Users\pc\My project (4)\Assets\Challenge 4\Scripts\EnemyX.cs 31 Active
dont blindly copy
it was example
whoops
you'll want to learn c# first before delving into scripting
Just Unity in general
the user has done visual scripting in unity before
ya basic c# will d o you wonders
hey
it worked all this time
but in the public field of the prefab, it just showed the initial value
you probably never saved before
I thought it was supposed to be shown in the public field when it changes
you mean in the inspector ? yes you should be able to look there for changes
not on the prefab , the instance of the prefab
yea it doesn't show on the instance of the prefab
when I pause and select a prefab in the scene, doesn't show
but debug log shows it works correctly
screenshot the instance in the scene with its inspector showing
compare debug.log with the inspector field
oh no
I'm showing the wrong variable
ffs
did you want to do speed = spawnmanager.enemySpeed
yea yea
I got it now
yea ofc it works now
I hate it when it's stupid mistakes
rather than complicated mistakes 😄
soon enough you'll get those too 😮
those are harder to undo!
so all this time the issue was I was looking at the wrong float, it worked at the start
Hard, but more fun, until it stops being fun and starts being pain
public void Attack3()
{
anim.SetTrigger("attack 3");
cooldownTimer = 0;
if (Input.GetMouseButton(2))
{
slashes[0].transform.position = slashPoint.position;
slashes[0].GetComponent<Projectile>().SetDirection(Mathf.Sign(transform.localScale.x));
}
}
Hii, how do I add a delay to the if statement?
3 ways
Time.time
Time.deltaTime
Coroutine
or ig Async delay but ehh
yeah I have good familiarity with unity, I've done shaders, animations, modeling, textures and everything else including programming with Playmaker
just confused by c# still
ight, ill look into those, thx
basic update timercs float time = 0; private void Update(){ time += Time.deltaTime; if(time >= maxTime){ //do something time = 0; } }
time -= maxTime I would do, not a big difference though
ah yeah that also hehe
Why that instead of just resetting it to 0?
preference
Well, it will discard the part that's more than maxTime and each repetition will become that much longer
interesting
There's also a case where maxTime is smaller than .deltaTime in which case the difference may be huge. if you do time -= maxTime, the time will keep increasing until the game speeds up enough to take care of all of those (likely never). If this is a concern, one should use a loop where while (time >= maxTime) time -= maxTime; to immediately take care of them all
Yeah fair, although seems to me like they’re making something like a combo so they probably would want it at 0, instead of a constantly running a timer they run it once when first attacking
yeah Im making a combo
I'm unsure what combo refers to in this case
Hi, I'm creating a tarot Chess game. I'm on the brink of starting a multiplayer. I have already decided on Peer to Peer as it's my first commercial product, and I don't have the money for servers in case my game would get around 400 active players. (I saw that on many sites more than 100 is paid).
So, it seems so complicated and hard to follow, and such things really effect my passion.
So, how do I even begin this?
I would like to understand the topic, but I'm also struggling with time, as I need to program around half of the gameplay as a side project in 3 months.
Any advice?
how do you know its actually going to be 400 active ?
Like in fighting games, punch after just punching does a second type of punch
Simple. Dont.
P2P is very difficult to implement and the vast majority of users will not be able to do so
Just a random number, but I don't want to worry if my game exceeds my expectations in few months/years
its an attack combo, each swing activates depending on which mouse button I press, I need the delay cause the flying slash starts at the same time as the third slash
But I want to have multiplayer, and I can't settle on paid servers. Is there a third option?
would be easier to then just start with the smaller tier / cheap monthly actives then upgrade as you see increase, by then you should be earning no ?
No. But the major server providers have a free tier which you could use as a relay server
if you aren't earning with 99+ active users to cover basic server costs then idk. ID think a better strategy
the slash spawnpoint being that far is because of a seperate problem i sent in animations
||also only slashing one direction||
For future reference, do I need to find the game object in reference or just get the component (script)
Hey guys, I dont know where to adress this so ill just do it here. I worked on this game for weeks, and I saved it yesterday and clsoed it, now I open it and this is what I see, what do I do?
yeaha, that was the porblem, the spawn point being that far was for clarity
I think you're confusing the term references with the inspector somehow
eg. making a reference vs assigning the reference a value are different,
no repo setup to revert the file to an older version and see, if that was the issue? backup the file before reverting
I'm currently a student, with little income, and I simply don't want to worry about the game all the time. I don't have much experience, and the game would mostly get money on skins. I'm not sure of my competence here lol. Will they sell? What if they stop? And thousand other 'What ifs'
P2P seemed as a solution so I don't have to worry about the game so much
Alright so if I wanna get a changing variable from another game object, do I only get tue script component in update or do I also need find game object in update
If you get the component once it will be up to date any time you grab a value from it, it’s just a question of if the object or component still exists
I mean, servers cost money and so unless your players are willing to open their ports to host games, you need a better strategy there.
You might be over estimating your active traffic, the free teirs might just do.. by time you get more player, you should be able to cover cost. If not again, you need a better monetization strategy
if only it were that simple, the vast majority of home ISP will not allow opening ports to incomming connections which is a requirement of P2P
How do I revert it?
This is why WebRTC is the new magic transport layer everyone uses
oh thats weird, I never had an issue. I'm in US. I had time warner and then fios
Btw it was years ago though maybe things changed, I use different provider and no longer open ports anyway
Do you have version control setup?
uhhh I dont think so
So I find the object in start and get component in update?
Or do you mean both in start?
I dont know what that is 🤷
Well, I plan to release paid story mode, and later release it on mobile that will have ads in some places. I don't know, I'm guess I'm too uncertain here lol.
I have what I believe is a great and fun idea and wanted to it in the beat possible way and also not worry about it all the time. But I'll look at paid servers once again
even WebRTC requires a server to establish the initial connection
true, you can use like some minimal relay server though like MQTT
pennies for a server
You can get both in start, but you should check in update if it still exists, because if you at some point delete the object it will error if you try to use the component
yeah, it sounds like you have confidence in it which is very good, so yeah don't let that be the only importance, many great games were ruined with bad monetizations / financial planning, had a few failed things myself and you learn from them. Just something to keep in mind, the business side of it will be just as important
Is there a better way to early-exit from a coroutine (inside the coroutine) than a goto? It's not particularly cumbersome but not particularly elegant either.
yield break
ohhh that's right thank you.
a coroutine is just enumeration loop
Yeah I don't use enumerators much, I always forget about yield break, appreciate it
Well, the only thing that I worry about is making the story mode directly 'paid', as it may piss off some of the players
You def. should get familiar with whatever version control, probably git to start off. But that does not help you yet anymore. Your file might be corrupted. Try copying it, moving it, maybe move the meta file and let unity regenerate it. Restart your machine
Git should be one of the absolute first things you set up in a project
Any type of version control is a massive help. Not just against corruption but also bug fixing and/or just generally testing stuff and being able to revert whatever you applied
If not null? Ok thanks
Does a component evaluate to null if it was deleted? I think so but now I’m doubting myself
its saying, this? it doesnt worrk
of course not, you blindly copied it lol
its just an example, you have to adapt the variables properly
do basic c#
oh right
yerp, even components pending destruction should evaluate to null iirc
also why did you do cooldownTimer -= 0
Cool, ty
typo
Yep, just make sure it’s not null
If it is still buggy, maybe try using DestroyImmediate() I may have been wrong about the pending destruction thing, they aren't technically destroyed until the next frame.
Are you trying to continue the combo after the timer or just to line up the animation? If it’s just to line up you might just want to use coroutines
just to line up the anim
You should probably just use a coroutine then, less logic to keep track of and you sleep a specific amount of seconds then do the attack
Actually does unity have animation events? As in trigger an event at a specific frame, If so that’s probably the better option
https://pastebin.com/HPePvkJj grab script
https://pastebin.com/UFaeAgpD lever script
https://pastebin.com/aeE4Gcf0 trapdoor script
the balance script I didnt include just have rigidbody2D.Moverotation()
problem is the lever going back and changing its limits.I cant pull it by grabbing but can push it with my body.
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.
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.
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.
If this information is helpful, there are different scenes on this project, and they work properly
this may also help
ngl, I have no idea how to do that yet, and I cant find how to use coroutines
Neither do I, but if you want to go the coroutine route, https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MonoBehaviour.StartCoroutine.html
someone corrected me and apparently destroying something destroys is at the end of the frame and not the next frame
Yes
I personally find the animation events kind of cumbersome and annoying to work with, but there are a lot of tutorials if you look up "Unity Animation Events" on youtube. Might work well for you. You will need to get an understanding of events (specifically Unity Events) if you want to use them well.
so instead of doing yield return null in a coroutine maybe you can wait for the end of the frame but im not sure if even that is enough
i kinda dont know many of the processing order of things but u can try it
i use animation events to play sfx in my animations and to tell my code when an animation is finished
not sure what ur problem is cause i havent read that much but animation events are super useful
and coroutines are really easy to do the basics so you could figure that out in a couple minutes too
You may find this resource helpful, I come back to this all the time
https://docs.unity3d.com/6000.0/Documentation/Manual/execution-order.html
It doesn't have everything but it does clear up some ordering problems
Just checked but don’t see anything about it, what’s the timing on event execution? Surely it’s not instant, like if you trigger an event in update when would scripts detect it being triggered
What events are you talking about? Animation events are in the upper section.
otherwise event listeners are invoked in order immediately after calling the Invoke method
Didn’t realize there are different types of events
Yeah that, didn’t think it would be immediate
They're all kind of essentially the same thing under the hood, but Unity calls the Invoke method itself automatically for some components, which is why I asked.
Yeah that’s basically what I figured
i dont know
I think its because of my grab script that adds a joint and then removes
maybe its limits are changing, no its not as I can see in inspector
Is there a chat here to talk about random stuff
Random unity stuff
You can make a #1180170818983051344 for that.
{
if (!IsGrounded()) //make the player fall down
{
velocity.y += gravity * Time.deltaTime;
transform.Translate(0, velocity.y * Time.fixedDeltaTime, 0);
}
else if (IsGrounded()) //make the player jump with force without gravity
{
transform.Translate(0, velocity.y * Time.fixedDeltaTime, 0);
}
}```
I am using this to jump the player but it falls beneath the ground when it comes down with the velocity. I am using raycast in groundcheck
Anyone know why i can't pick this mesh up, but i can pick up the cube?
(I am incredibly new btw)
when posting !code, use paste sites or format small code blocks. use http://streamable.com or save as mp4 to post videos . . .
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh crap, sorry 😅
<div style="position:relative; width:100%; height:0px; padding-bottom:56.250%"><iframe allow="fullscreen" allowfullscreen height="100%" src="https://streamable.com/e/fyz9y9?" width="100%" style="border:none; width:100%; height:100%; position:absolute; left:0px; top:0px; overflow:hidden;"></iframe></div>
Watch this embedded Streamable video.
on line 52, a reference variable is null (is not assigned or does not exist) . . .
make sure it is assigned before using it . . .
I followed a tutorial. So i'm not sure how i do that
wait, do you know what a refernce variable is?
did you follow or learn beginner C#? that very important when trying to code . . .
a reference variable is a variable that references something right
i didnt. but a reference variable, is that like this?
They seem more like public variables, cus they reference actual values rather than an object
Is there a script that you should be using here? if so, drag it there
typically, a variable reference is a class or an interface . . .
Pls share the full code and not tiny chunks
to make it easier. there is only one variable on line 52, so that has to be the reference variable . . .
So many screenshots and I have no clue where CurrentObjectRigidBody comes from
Like in the script one?
yes
and share us the full script please
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
also, one of your scripts is missing . . .
the answer lies here . . .
A tool for sharing your source code with the world!
if(CurrentObjectRigidBody) does not do what you think it does
-if(CurrentObjectRigidBody)
+if(CurrentObjectRigidBody != null)
This is probably what you intend
i just followed a tutorial, i have no idea what i am doing
Then you either use a very shit tutorial or you made a mistake there
You have explicitly compare against null. Your current if-statement doesn't do that
If you fix this, it seems to assign CurrentObjectRigidBody in the else-statement and fix the issue
This has to be done on both line 28 and 60
when following a tutorial, make sure you understand each line of code before proceeding to the next line. it doesn't make sense to continue a tutorial if you don't know what you are doing . . .
so put if(CurrentObjectRigidBody != null) on line 28 and 60?
This code makes no sense in general
What is happening here?
You definitely miss something here
And line 52 has the actual exception
Same if-statement must be added, maybe?
There's nothing wrong with the syntax
i meant the CurrentObjectRigidbody thing
Anyone can help me a bit?
hmmm, i believe (CurrentObjectRigidBody) will implicitly check for if it exist and if it's null . . .
you shouldnt manually change the transform for this kind of thing afaik
then what?
kinematic bodies won't check for collisions
On second thought it probably does
Raycast does
But stuff like that is such a weird check to do
Raycast detects the ground check
Just specify null explicitly. Now it's a question if does what you think it does you see
if it falls below it
But the issue is probably that something misses when they enter the block scope here
@dawn hedge you should check that
You are probably missing an if-statement there
On line 50
lemme rewatch the tut rq
You have null checks in the script which prevent this, except for this one
I see, I misunderstood your script at first. That block of code looks fine but there are a number of potential problems with the ground check code. Also, you'll run into problems when the character has to move laterally.
1- Make sure the ray won't hit the backfaces of your character's collider
2- Make sure velocity isn't building up while you're grounded
3- Make sure the raycast is emitting from the right spot, in the right direction (use Debug.DrawRay for that)
4- Make sure the raycast isn't starting from the surface of the ground collider, it won't return hits with a distance of 0
yea as u said it will probably go past the floor and only then will the raycast detect it so getting something to snap your player back is another question. Which im not sure of but its just a weird way to do it in general
a tip for making your game development learning more fluid is to learn how to code. I'm a total newbie with C# and Unity but I learned how to code in other language before
Wait I fixed that with the below code
{
// Ground Check
isGrounded = IsGrounded();
if(velocity.y < 0f && isGrounded)
{
velocity.y = 0f;
}
}```
and c# has been way easier to learn than I thought, easier than C for mexD
my broski, I have a game where i need to have the player isKinematic = true. With that I cannot use the default gravity to make player jump
Because I require physics forces to be detected properly on my player
and its kinematic so the movement happens smoothly
hol up
else if (IsGrounded()) //make the player jump with force without gravity
{
transform.Translate(0, velocity.y * Time.fixedDeltaTime, 0); // if the character has a negative velocity, it will clip through the ground during this step
}
thats why he wants to snap the player back
@lavish kernel this fixed
yes
Ah, in that case you need the hit.distance value from the raycasting code, you can figure out the rest based on what you've showed lol
i tried that but it didnt work out,. what worked out for me is I set the velocity = 0 if its negative
Well your velocity's y component can't be negative if you're on the ground. the hit distance is key here. You've got it broski
yeah
Thanks everyone
(I don't know your use case but you may also be able to make a copy of your character's collider that's kinematic and doesn't collide with your player, as a workaround to your player collision problem. Then your character itself can be a non-kinematic body)
yeah didnt think of it... But im sure this works as well
Yeah, I had to fix this for my extension methods. I have IsDestroyed use a boolean check on a unity object to specify a check for destruction (if an object exists), and IsUnityNull to use object.ReferenceEquals() to check if it is assigned (is null) . . .
How should I start learning unity?
learn c# basics then !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hi Folks, I am facing an issue when my player is jumping (In Air on the moment), it is unable to move. While on the ground it moves as expected. Now I am using RigidBody.MovePosition() to move it horizontally, and transform.Translate() to move it vertically (Jump and making it fall down with a custom gravity).
Here's the code for your reference: https://pastecode.io/s/8hns6wbh
Suspected Lines: Line No. 68 for movement, and 123 for jumping
manipulating the transform does not use the physics engine. you can't do that if you're using physics to move your object . . .
What can i do?
Nope, my body is kinematic
you can assign the velocity or use AddForce with Impulse ForceMode . . .
i suggest assigning the velocity because your custom gravity code should affect/use your velocity instead of transform . . .
basically, use MovePosition for movement and set velocity for falling and jumping . . .
where add 1f? i need this script after time
public GameObject Beginer;
public void whenButtonClicked()
{
if (Beginer.activeInHierarchy == true)
{
Beginer.SetActive(false);
}
else
{
Beginer.SetActive(false);
}
}
"after click"
{
// Apply gravity if not grounded manually when kinematic
if (!isGrounded)
{
velocity.y += PlayerGravity() * Time.deltaTime;
}
else if (velocity.y < 0f) // Prevents "bouncing" after landing
{
velocity.y = 0f;
}
// Update position based on velocity (for vertical movement)
Vector3 newPosition = rb.position + new Vector3(movement.x * moveSpeed * Time.fixedDeltaTime, velocity.y * Time.fixedDeltaTime, 0f);
rb.MovePosition(newPosition);
}```
This Works but again it makes my object fall under the ground @cosmic dagger
just remember not to override rigidbody.velocity.x and rigidbody.velocity.z when assigning the gravity/jumping . . .
In 3D, MovePosition is no better than setting rb.position directly (for non-kinematic bodies). I would highly recommend using .velocity instead
i don't understand? you deactivate the Beginer GameObject if the condition is true or false . . .
1f is not valid anywhere in this script. Please be more clear in what you're trying to do.
i just need after 1 second set active false
use a Coroutine. look at tutorials for how to use . . .
Eh, nevermind. This page just lists error handling
@cosmic dagger Well, it does interpolation for smoother visuals but otherwise no better
they are different:
MovePosition is for continuous movement and it takes interpolation into account for smooth movement
Rigidbody.position teleports the object using the physics engine to avoid recalculating the position of all collider objects in the hierarchy . . .
In 3D though, MovePosition doesn't respect collisions
In 2D, MovePosition actually changes the velocity
That's what I mean, it looks smoother but doesn't make difference physics wise
yes, you have to code your own collision system to detect obstacles. that is a con for using a kinematic rigidbody . . .
If you intend to use a kinematic body then you are expected to do your own collision checks (such as CapsulaCast/Rigidbody.SweepTest)
I see
this
I see, for kinematic (edited) bodies, using MovePosition is good
I thought they were going for the velocities and forces path
no problem; they were already using the kinematic approach. i just suggested a fix for applying gravity and jumping to fit what they were using . . .
guy i been switching from visual studio to visual studio code. i install every extension for C# but some reason the type that detect error doesn't do it job, like you see on the image, i typing random but it say there no error. i mean i still can program normally but not seeing where the error is, was annoying. can anyone know how to fix this?
You should follow the steps to configure your !ide 👇
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
double whammy . . .
hi - can someone help, doesn't work up Force private void AttackPlayer()
{
//Make sure enemy doesn't move
agent.SetDestination(transform.position);
transform.LookAt(player);
if (!alreadyAttacked)
{
///Attack code here
Rigidbody rb = Instantiate(projectile, transform.position, Quaternion.identity).GetComponent<Rigidbody>();
rb.AddForce(transform.forward * 32f, ForceMode.Impulse);
rb.AddForce(transform.up * 20f, ForceMode.Impulse);
///End of attack code
alreadyAttacked = true;
Invoke(nameof(ResetAttack), timeBetweenAttaks);
}
}
Have you tried debugging the function &/or the if statement within it?
no, i do it like in video show, and my projectile when created just fall down
What happens if you try giving it a much larger force? Try multiplying it by 320 or 3200 instead to check the force is being applied
Also use debugs
ok i will try
what does "doesn't work" mean?
Is the function doing absolutely nothing?
Is it even running? Log something to check that
no, in video projectile shoot from enemy in diagonally, but in my case its start from enemy center and like magnet fall down
forward force work well, up force - not
like that
but in scripts should be like that
the AddForce calls look fine to me. I guess I would try larger numbers to see if anything changes, as Tye suggested
i change up force from 8 to 100 and now its ok but shoot back)))
forward force was 32 when i up it to 64 he shoot forward but with the same problems from beggining)
It's possible that the projectile is colliding with the enemy
Especially given that you're instantiating it at transform.position
you are genius)))) i forgot to delete box collider from glasses))))
ah, that'll do it
that was))))
I'm about to sit down to make a start on a UI system for a project. I need to include different SOLID principles, as well as design patterns. I'm really struggling with the latter and where to fit which ones, could someone recommend some for me? It's going to be a simple system - shows the score, current theme (word game), will have pop ups when the player gains points (like a "+1" pop up underneath the score text), and will show the count down timer.
It will also have animations, but I don't think it makes sense to not use Unity's animation system
So far I've basically just got Singleton and Factory (these two I understand) but I don't know what else to use? It seems to me like most other ones are niche usecases
Dont use some design pattern just for the sake of using a design pattern
You shouldn't be trying to "catch em all"
When you encounter a problem that a particular design pattern can solve, you use it
I know, but that's what the project requires unfortunately - same goes for SOLID.
I also don't think it makes sense
okay, so this is academic
Yes. To be more clear the uni project requires SOLID principles and design patterns to be showcased in a few word "mini"games. Maybe I'm just not thinking outside the box enough in terms of the ideas?
Just use MVP or MVC for your UI. (Not something you would do in practice though)
You can also use the strategy pattern for something stupid like having two different behavior for the score.
And potentially the Observer-Observable pattern for the communication between your system.
Also, Flyweight pattern is pretty easy to implement. Just use a ScriptableObject somewhere that is used twice.
Thank you! I'll take a look
Am I correct in understanding that MVP would usually be used in software as opposed to games?
Yes, even then you usually more modern framework that utilize MVVM instead.
In Unity, specifically, the V and C mostly merge together.
Having a difference between the UI and the Logic of the game is common though.
So would it be essentially just separating UI elements from the actual logic?
Yeah, without really having something in between.
I think there was another pattern somewhere... mediator maybe? that acts as a middle man or something like that
maybe I could fit that in there as well
Yeah, never really used it explictly honestly.
It simply is natural to have object that are central.
Ok I'll dive in and try to use those, thanks a lot!
By example, I usually have a [Start/Home/Pause/...]View Monobehaviour that encapsulate the UI. That would be a mediator
A fun demo would be to completely delete the UI and have your game keep running (just...without anything visibly happening)
Hey, need some help real quick with coding. Currently, I have issues regarding the DealerHandValue not changing the actual value of the Dealer's hand. Currently, it always says 0, even when DealerNewHandValue has the correct value - it won't change the Dealer's hand.
Here's the main code that is having issues:
public void DealerCardValueChangeCelestialBond()
{
Debug.Log("DealerCelestialBondReset");
foreach (Transform child in Dealerhand.transform)
{
Destroy(child.gameObject);
}
dealerHandManager.GetComponent<DealerHandManager>().dealerCardsInHand.Clear();
Debug.Log("Clear Value");
Dealerhand.GetComponent<DealerCardValue>().DealerhandValue = 0;
Debug.Log("ClearValue: " + DealerhandValue);
DealerhandValue = SpecialCardObject.GetComponent<SpecialCardScript>().DealerNewHandValue;
Debug.Log("PostClear DealerHandValue: " + DealerhandValue);
}
}```
DealerNewHandValue always works, it is ONLY DealerhandValue. I don't really know why. Any ideas?
firstly why soo many get components
second im not sure i understand the issue as i dont see the connection between these hand values
Sorry, I really don't know how else to do it 😅 How would you do it? Just save it to a variable?
Im guessing you didnt serialize the objects as the script type but as GameObject
best to go change that to start because GetComponent() isnt free and ofc if you accidently have more than 1 of that component on an object it gets the first.
[SerializeField]
MySuperAwesomeComponent comp;
Wait so how would you call that? Would you put in the gameobject inside that SerializeField? Or is it jus the script?
yes? if you drag the game object to it then it will become the component (if on said game object) OR you can drag the component itself there
not as hard as you think it is
That...makes more sense. Let me try that real quick.
Seems to be common thing people dont seem to know about and im not sure why 🤔
Some shit asset store stuff i have seen have never serialized components...
But also, how do you think its not connected? I was thinking it would connect with this line:
DealerhandValue = SpecialCardObject.GetComponent<SpecialCardScript>().DealerNewHandValue;
there is too little information to understand the problem...
This confuses me for example, you set a field with the same name elsewhere then log the value on THIS component?
Dealerhand.GetComponent<DealerCardValue>().DealerhandValue = 0;
Debug.Log("ClearValue: " + DealerhandValue);
That was me just being dumb 😅was just moving the script to figure out where it could work, didn’t remove it. Just did, thanks for catching that.
Basically for the confusion part, it's a little weird. Here is the script attempting to get the value from SpecialCardObject:
DealerhandValue = SpecialCardObject.GetComponent<SpecialCardScript>().DealerNewHandValue;
Which accesses this:
DealerNewHandValue = handManager.GetComponent<HandManager>().handValue;
Debug.Log("DealerNewHandValue: "+ DealerNewHandValue + " PlayerHandValue: " + handManager.GetComponent<HandManager>().handValue);
BetManager.GetComponent<BetManager>().ResetCurrentHandCelestialBond();
Debug.Log("ResetHandCelestialBond");
Dealerhand.GetComponent<DealerCardValue>().DealerCardValueChangeCelestialBond();
Debug.Log("DealerNewHand Value: " + DealerNewHandValue + " DealerHandValue " + Dealerhand.GetComponent<DealerCardValue>().DealerhandValue);
Horrible coding, I know, going to fix it with what you said. Basically, it saves the player's card value, then saves it for the DealerNewHandValue, then resets the player's hand. Then resets dealer's hand, but with the new card value
removing all those GetComponents() will make it a lot easier to read 🙏
or get em once in the function
are all of these variables GameObjects...?
you can reference the component type instead
dw already told em
Yeah, fixing it right now
Code to change DealerHandValue:
DealerhandValue = SpecialCardObject.DealerNewHandValue;
}```
The connecting thing:
```` public void CelestialBond()
{
//Swap hands with other player
DealerNewHandValue = handManager.handValue;
Debug.Log("DealerNewHandValue: "+ DealerNewHandValue + " PlayerHandValue: " + handManager.handValue);
BetManager.ResetCurrentHandCelestialBond();
Debug.Log("ResetHandCelestialBond");
Dealerhand.DealerCardValueChangeCelestialBond();
Debug.Log("DealerNewHand Value: " + DealerNewHandValue + " DealerHandValue " + Dealerhand.DealerhandValue);
}```
Here we go. Heading to class right now. Just @ me, Ill look at the messages in a second! Thanks.
I tried creating an elevator but when I step on everything but Player obj falls into the void. Player/camera setup is from a youtube tutorial.
Player: rigidbody, Player obj: mesh + collider, orientation: empty game object, Camera Holder: transforms position based on Orientation, Camera: Camera.
Only the Player obj with the collider mesh is being parented to the platform. how do I fix this so everything moves with the lift? https://paste.mod.gg/acuzdovzvurr/0 code being used by the lift
A tool for sharing your source code with the world!
Well your code is pretty explicitly setting the parent of the object with the collider
Since that's a child of the main player object, well you see the result
You could change it to grab the root instead or the parent of the object with the Collider, or use GetComponentInParent<Rigidbody> to find the object with the Rigidbody and then parent that object instead
You would also need to change your Rigidbody to be kinematic for example though
Otherwise it won't play well with this
Another option is to make the lift an actual physical object with its own Rigidbody instead of doing this parenting thing
this probably sounds the easiest, thanks 
How can i "select" a button by using code? i searched the documentation and googled it but couldnt find anything.
You want to use SetSelectedGameObject, on the event system component
EventSystem.current.SetSelectedGameObject(whatever)
note that you don't select a Selectable -- go figure
note that google will often give you old docs from when the UI components weren't in their own package
mostly still accurate, just annoying
ty
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/index.html
This is the new package documentation
wdym something that isnt a Selectable? arent all buttons selectables?
Yes, Button is a kind of Selectable
You can make your own custom selectables too
I've done that for my settings menus
Why does my null check fail?
foreach (Buttons _button in buttonHolder)
{
_button.button[0].SetActive(false);
if (_button.button[1] !=null)
_button.button[1].SetActive(true);
}
What do you mean by "fail"?
Index was outside the bounds of array, sorry I should have clarified that clearer
How can I add something to the On Click () thing through code? like running a function
_button.button is presumably an array or list and you're accessing [0] and/or [1] which are outside the bounds of that array or list.
Literally nothing to do with the null check
that is one cursed foreach
myThing.onClick.AddListener```
oohh. too slow
tysm
Hey, for some reason it's giving me a null object reference debug log. This is a new thing for me (not the reference, just the hand.handValue). What do I do? It's flagging for this:
[SerializeField] public CardValuesScript hand;
public int handValue = 0;
public int cardCount;
public List<GameObject> cardsInHand = new List<GameObject>(); //Hold list of card objects in our hand
public void Update()
{
handValue = hand.handValue;
}
which line is line 28?
fyi [SerializeField] + public is redundant
handValue = hand.handValue
How do I make it work then? Whenever I was talking to other people they were saying I should do component based so I dont have to do GetComponent(). Should I just keep it a gameobject?
I have no idea what you mean by that question
you make it work by assigning a value to hand so it's not null
Or... the instance of the script pictured in the inspector your screenshot is not the one that is throwing the exception you see in the console. It's a different instance.
at some point hand is not assigned, make it not do that. or if you make it null on purpose put a null check
or that yes
Also definitely not getting destroyed - that would be a MissingReferenceException. Or in this case no exception at all.
in this case no exception at all
how come?
Simply accessing a field on your script doesn't trigger any of the built-in Unity checks that result in MRE
If you accessed a unity property like .transform it would
This is what I have for the hand - Handposition is an object. Is it because it's not a gameobject?
The instance of the script pictured in your screenshot is not the one that is throwing the exception you see in the console. It's a different instance.
Is it because it's not a gameobject?
Get your mind off whatever track this is, it's not relevant
wouldn't dereferencing it (hand.handValue) cause an error if hand was destoryed though?
no, since it's just a simple field access and Unity has no way to intercept that
ah right yeah
dont you get a "such and such was destroyed but you're still trying to access it"
or is that just transforms..
Whenever I click it though, it goes to hand.handValue? Weird. Trying to figure out what's calling it
When you click what
Search your scene for HandManagers
you probably have more than one
well yes that's the stacktrace does
t: HandManager``` in the hierarchy search bar
I just have this one, which is the one that i showed you
ok then yeah your code is setting the hand to null at some point
or there's an instance of HandManager that is being spawned at runtime
Debug.Log(hand, this) check when it goes null maybe? (must go above/before you try to access it)
How? thats so weird. Ugh, never had this happen before, sorry if I seem rude (I dont mean to be.)
How what
hand = null;
is one way
or hand = somethingThatResultsInNull;
Showing your code would be a good start if you want effective help
(the full script)
https://paste.ofcode.org/zsbV56Fhg5svA7DzgBjc8J Here you go - thanks for offering to help though
when does the error happen exactly?
Is it right away or when you spawn a card
As soon as Update() is called
right from when you play the scene?
Yes
Are you sure there's only ONE HandManager component on that object?
Okay, now it's magically not doing it on HandManager? Ugh, so weird. I don't know what fixed it. Checking for any empty things rn...
i dont see you assign hand anywhere?
unity goblins
it's in the inspector
maybe copied from somewhere
hello everyone
I didn't know it would make it public, still very new
serializefield is added to private variables to make them show in the inspector
without having to make them public
unless they need to be accessed from somewhere else, you should try to keep them as private
did someone had error: CS0246 before??
[SeiralizeField] doesn't make things public
It makes them serialized
i have it in my code and i dont know what to do
we dont know codes, you have to show error message
use English words we are not computers. I'm sure many people have had it.
yes you used something in your code that doesn't exist
or you're missing a using statement
and i dont know what of those 🙂
on line 19 of player_movement.cs
(are you missing a using directive ??? )
yea let me see
It's simple - you can't use types in C# that don't exist
is that part of InputSystem..oh issa struct
like if you wrote:
Bagel b;``` that would be an error if you never defined a type named `Bagel`
that's your error
but with PlayerActions
i mean i added these and now when i am deleting something with 'PlayerActions' i have more errors ughhh
Yes if you start pulling code out at random it's likely to cause more errors
It's better if you try to understand
you could tried to just fix it by using IDE quick actions, see if it finds namespace it belongs to
yes programming is hard
I recommend following this stuff to get a grasp of the basics first:
new InputSystem is also not very beginner friendly..you jumped into a shark tank right away..
Right now you're working with basically 0 knowledge of what you're doing
thanks i will see
oh i just wanted to do 2D game but i think i need to start frome basics
Yes
everyone needs to start from basics
2D games and 3D games are equally complex
Hey, i am searching how to do a script for a shotgun just like in this video https://www.youtube.com/watch?v=OMrBfGi5Res
Someone can help?
Please
Adding and testing weapons in FPS game made in Unity
also check out the paths https://learn.unity.com/pathways
they mix in a bit of both c# and unity components
essentials path is fixed..yippy
tysm
what do you want to know exactly, there is a few steps involved there
generally you can loop through a certain number and create a ray / bullet per each with slight offsets
i am a beginer i just want to know how to do something like that
well there is a lot of code to know, you might also benefit from unity learn website
there are a bunch of gun tutorials on youtube
I tried this one but it gives me a error
How to make ALL kinds of GUNS with just ONE script! (Unity3d tutorial):
Here's how to make one script,, which lets you create any gun you like :D
All of the Links ^^:
My Discord: https: https://discord.gg/5S3bBBq
Download CODE: https://www.dropbox.com/s/g077hpelcdnjyqm/GunSystem.cs?dl=0
Brackeys video: https://www.youtube.com/watch?v=9A9yj8KnM8...
you can learn by doing tbh
yeah but some basic knowledge is needed, like how to properly type the syntax and basic c#
unless you dont even know the basics of unity yeah
i guess you copied the code wrong
yes you blindly copied without knowing you have to actually create types beore using them
time to drop this and go to !learn first
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
also a compare tag and get component, tutorial is shit
they never heard of TryGetComponenot or caching the component as a specific check ?
316k views tho.
What is the comand for destroying a game object
like in game or in hierarchy??
you could easily google that
like fr fr. dont be lazy
ik lol but it this usualy faster than just getting a fhole page that i have to read
pretty much
its called "researching" it helps you learn.
ChatGPT at least
ChatGPT is also good
Thats even slower
BUt anyway see i got another pesrson to gogle it for me and i got my answer in less than 30 sec
That attitude will stomp down your learning curve to a flat line 😄
it will give you a short answer
wow nice lazy guy
next time people wont be so nice..
it will also get you blocked by most of the people who could help you. bye
true
ik i ussualy learn everthing i just wanted the comand lmao chill guys
but you could just google it dude😭
you can believe that for yourself. And what steve said also fits for me 😄
@mystic lark the 1. rule in #854851968446365696 is: "Search the internet for your question!"
lmao
yes ik leave it alone i wont do it again i get it
ok gl with code
how i do this code block??
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ohh i see tysm
Read the bot message for proper fornatting
is there any way to make a health bar linked to an enemies health if i'm using two different scripts or sohuld i just put them in the same one ? 😓
of course
default is always gonna be yes , most of the time
im lowkey cooked i've been stuck on this for 40 minutes and im mad lost 😓
Have the two scripts communicate with each other. That's the basics of how most things in most games work.
i think?? i've done that , the enemies taking damage and dying but it isn't shown on the health bar which is a bit unfortunate
you'd have to share your code and what's going wrong etc if you want more specific help
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
A tool for sharing your source code with the world!
you don't put ``` if you're using a paste site
also you commented out the class declaration?
and that second link is just the blank pastebin link
oops
did i
Just copy and paste the whole thing yes lol
are TakeDamage and Heal being called at all?
Ok it's really confusing what's going on here
which script is supposed to do what here?
What is the role of each script?
And which object(s) are they on
enemyhealth is for the enemy to take damage and do the sprite anims
on the Enemy object
The fact there are two variables that seemingly represent the current amount of health you have:
public float healthAmount = 100f;
public float currentHealth;
This is very problematic
ok that just seems like manage health 1 and manage health 2
you need to have one source of truth
and the Health1 is on a HealthManager object (i was told to put it on there)
and is supposed to be reflecting the damage onto health bar
don't forget public float health;
no i was thinking of that and getting rid of it
did i put too many variables 😓
Yeah it's super unclear which one of these variabels actually determines what the current health is
that do the same thing
yes
you might want to consider health and maxHealth instead
okaydokes
those are the typical terms used in games
I would expect:
- One script on the enemy that actually manages the enemy's health situation
- One script on the UI that handles displaying the health from the first one in the UI
that's it
okaydokes
And name the scripts clearly like:
EnemyHealth and HealthBarUIHandler or something
Health1 is very vague and doesn't telll us what this thing is supposed to do
okaydokes
ill change them up
so i should remove a variable and make one variable i'll use through both scripts?
Yes, the scirpt that actually manages the enemy's health should be the only one with a variable that represents how much health the enemy has.
the other script can read that information from the health managing script as needed
okaypokes so the health managing one shouldnt actually interact with the health other than displaying it ?
One super simple example:
public class EnemyHealth : MonoBehaviour {
public float Health { get; private set; }
public void TakeDamage(float damage)
{
Health -= damage; // minus the damage from healthamount
Health = Mathf.Clamp(healthAmount, 0, 100); // check healthamount is within valid range
}
public void Heal(float healingAmount)
{
Health += healingAmount; // Add healing amount to healthAmount
Health = Mathf.Clamp(healthAmount, 0, 100); // Ensure healthAmount is within valid range
}
}
public class HealthBarHandler : MonoBehaviour {
public Image HealthBar;
public EnemyHealth enemyHealth;
void Update() {
HealthBar.fillAmount = enemyHealth.Health / 100f;
}
}```
it shouldn't care or know about the health bar at all
This isn't exactly what I would do but it's very simple and will work
okaydokez ill try my best and if it comes to it i'll use that one
thank u very much :)
is there a way i can stop the timer ?
So somebody at some point recommended me to Newtonsoft to write classes to json as savedata
I'm having an issue where I have this class:
// Put here all the flags you need for the story
public enum EventFlag
{
TestVar_HasCrossedPlane,
TestVar_HasInteracted,
HasLighter,
HasLantern,
HasSeed,
HasCrayon,
HasWateringCan,
MuseumEntered,
MuseumExited,
IntroDialogueEnded,
GodDialogueEnded,
ManDialogueEnded,
TreeDialogueEnded,
NakedDialogueEnded,
PowerDialogueEnded,
ReturnDialogueEnded,
SeedDialogueEnded,
SelfDialogueEnded,
EndDialogueEnded
}
public class EventFlags
{
private List<bool> events = new List<bool>();
public EventFlags()
{
for (int i = 0; i < System.Enum.GetValues(typeof(EventFlag)).Length; i++)
{
events.Add(false);
}
}
public EventFlags(EventFlags eventFlags)
{
for (int i = 0; i < eventFlags.events.Count; i++)
{
events.Add(eventFlags.events[i]);
}
}
[Other methods...]
}
And when I try to serialize it like this: JsonConvert.SerializeObject(flags)
I just get {}
Does newtonsoft not support lists?
pause it?
yea thast what i mean is there a way?
yeah just stop counting
i'm pretty sure that private fields are not serialized by default and you need to slap a JsonProperty attribute on it
you wouldn't have to, no.
DAMN yeah that was it
and how would i do that?
true but i would
hes joke
im not
brutha
add a conditional or something to make it not count when you don't want it to count
i was thinkinng of something like that but i think i found i way
Thank you so much
Have you heard of if statements?
is there anything to replace drag in the new version of unity?
Drag still exists in the new version of Unity
did you look at the docs and/or read the error that said the drag property was obsolete?
it's not in the rigidbody anymore
linearDamping in the latest versions actually
i see linear damping
yes it's the same thing
damping is a better name for what it actually always was
it never behaved like real life drag
does the linear drag work if you're on the ground? I feel like it doesn't do anything
it works everywhere all the time
linear drag is applied all the time. it's friction that is only applied when contacting other colliders
that's strange
i put my linear damping to 0 but my character still stops when i let go
so its the friction i need to adjust?
sounds like a problem with your code, or yes it's friction
im dont evne have it coded, just using the sliders
wdym just using the sliders? aren't you setting the velocity of the object directly?
that would obviously not behave the way you are attempting to make it behave
which sliders are we talking about
You have code that moves the object
that's the code I'm talking about
But yeah this is probably a friction thing
it's also 100% the issue if they still have the code they showed a couple days ago where they are just setting the x velocity to the state of their digital input with no smoothing
i cant i remove this tile from the pallete? i accidently added it and the shift click thing isnt working
not a code question
i'm sorry but can you explain why this is a problem
you're assigning the velocity directly, including when your input is 0. so when you have no input you set the x velocity to 0 which means there is no drag or friction affecting it at all. if you want forces to act upon the object then consider moving it via AddForce or just don't assign to the velocity when there is 0 input so that forces like drag and friction will slow it down
ah
i did ```
void Move()
{
if (!isDashing)
{
/* if player is on ground or rail, have holding diagonally affect the same as just horizontally
otherwise just use the x input that comes in normally */
float adjustedMoveInput = isGrounded || isOnRail ? (moveInput.x == 0 ? 0 : (moveInput.x > 0 ? 1 : -1)) : moveInput.x;
rb.AddForce(new Vector2(moveInput.x * playerSpeed, rb.linearVelocity.y));
Debug.Log(moveInput.x);
// rb.linearVelocity = new Vector2(adjustedMoveInput * playerSpeed, rb.linearVelocity.y);
}
animator.SetBool("isRunning", true);
}
ignore the adjustedMoveInput it's not being used
i am trying to delete all clones at once with button press but its showing me this error, but its perfectly fine deleting in the OnTrigger. I tried searching but i cant to find the solution
the script is attached to the clones
you're calling that method on a prefab
when i change the first f nothing special happens just moves vertical normally but when i move second one my object disapears someone know why?
hello, I am unsure why this happened, but seemingly all of my scripts can no longer be found by unity. I am still able to access and edit them, but they can no longer be attached to objects. This isnt a script name issue as it is happening with even new and old scripts that were working before. any help would be appreciated.
- make sure this is not in Update otherwise you are adding way more force than necessary
- log the velocity and input to make sure you are understanding what is actually happening
you nee to start by getting your !IDE configured 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
I have tried these for the most part. There are compile errors but i cannot resolve them as editing the scripts do nothing, reimporting didnt seem to work nor restarting. this isnt just one script so the rest dont really apply
screenshot your entire console window
I put it in FixedUpdate()
i was renaming some stuff which is what originally caused that error to happen, but because my edits no longer apply, i cannot resolve them
well it seems the issue is just in your RoomSpawner and HallSpawn script trying to access something called structures in your RoomTempelate script. and provided you actually save your code, your edits will apply. you just have to fix all of the issues so it can compile
that script is currently completly commented out as an attempt to see if it would stop atleast those errors from applying (i know that it would cause other errors, but i wanted to test to see if these ones would stop showing up)
prove it
notice how that is an entirely different file than the one the error is complaining about
so when would you want to manually set the rb.linearVelocity vs using rb.addForce
this is the script that is trying to access room template.
that is neither RoomSpawner nor HallSpawn
please actually pay attention to your errors (and also the responses you receive in discord), you may find that the issues are actually pointed to exactly
jesus christ dude you are so aggresive
and no, that did not resolve the issue, i will ask someone else
He's right though. You need to learn how to actually interpret errors.
you may want to look up the definition of aggressive, as that was definitely not it. but if you want to throw a fit because i'm not spoonfeeding you the answer and instead telling you where you should look, then i'll just not help you further. and yes this is the aggressive bit
what a dick head
i'd bet if you were to actually show the two files that are mentioned in the errors we'd find you didn't fix them at all
both of those files were also commented out btw, but again, ill take the issue somewhere else
you need to actually fix the real issue, if you comment out a whole file the class def is gone.... so another error is probably going to show up instead.
if you can see a small bit of code that when commented out will resolve all compiler errors then thats an okay temp solution
can someone take a look
unsurprisingly, deleting a class will cause great confusion for every other part of your code that was using that class
(solution: delete those too!)
at that point, delete the whole project and start over
hardcore programming: start over from the beginning each time you cause a compile error
rougelite programming: restart the whole project each time you cause a compile error
(see also: fuckit.js)
I thought that learning C# would be hard because I only knew js but it seems quite easy so far
Are you coding flappy bird
yes lol
well, same family of languages, and knowing programming in general does help as well
By what it seems you need to reference the gameObject you wanna destroy. It would be better to store them in an array like so
TheComponent[] theComponent = FindObjectsOfType<nameOfTheClassOfTheObjectsYouWannaDestroy>();
And then perform a for loop to destroy them one by one
thanks vm ill doo it
What objects do you need in a collection? I would add the objects to a list when they are instantiated (or activated on scene load). Then you can just reverse iterate the list and destroy them . . .
I started to code c# and unity this sunday so idk😭
same lol
you only need to do reverse iteration if you are removing them from the list as you go, mind you
I'd just do
foreach (var whatever in stuff) {
Something(whatever);
}
stuff.Clear();
I usually also just add a continue guard clause against null
but yeah
foreach (var whatever in stuff) {
if (!whatever) continue;
Something(whatever);
}
stuff.Clear();
Hi , how can i do these class like that please and what is the name of that ( Scriptable Object ? something else ?)
that is a scriptable object
Are those checkboxes public bool variables?
they may not necessarily be public though, they can be private with a SerializeField attribute to expose them to the inspector
Thx
is there a way to use rb.linearVelocity = ...
and still keep linear drag
or do i HAVE to use rb.addForce
i still cant figure out why my player can't move back with rb.AddForce, only forward
it depends on how/when you want the drag to apply. you can either compute it yourself and just apply the velocity manually, or if you only want the drag to apply when you've released the button then do what i told you earlier
show what you tried as well as your debugging attempts
sure 1 sec
make sure to show the full !code using a bin site 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
A tool for sharing your source code with the world!
I tried using rb.AddForce
but it only goes right, left should work but it doesnt
also when I dont add a friction object to the player he cant move at all
when I do that issue occurs like i stated above
Ok but i would like have same the left screen, why mine is like a normal class ?
why are you still doing this (moveInput.x == 0 ? 0 : (moveInput.x > 0 ? 1 : -1)) : moveInput.x;
ah yes "didn't work" how descriptive
@mystic lark As someone who learned C# along with Unity and no prior programming knowledge, I found it to be relatively easy (the basics), but it solely depends on your discipline and willingness to learn
If you don't have that, it's very difficult as there is no time frame or estimate for how long it takes. Motivation doesn't help as it only inspires you to work, not actually do it . . .
i mean i have no idea how to describe it like the player just wouldn't move properly
even if i just use moveInput.x it doesn't make a difference
the same issue occurs
well if you can't describe it then nobody can help you 🤷♂️
so I don't think it's that
anyway, i told you earlier to log your input and velocity so you can get a better understanding of what is happening. so you've gone and removed your log for the input and are now only logging the velocity
log them both at the same time, that's the whole fucking point of doing so
it says in the docs. but, right click the project window and create a new one
sure
usually i'd send an example but i dont have any scriptable objects in my current project 
The left is an instanced asset of the ScriptableObject. The right is the script.
for the velocity
and what is the value of playerSpeed
To make an instance, in your project explorer, right click -> Create -> (the CreateAssetMenu parameters you defined in your class)
You need to use CreateAssetMenu on the class and create an instance of that ScriptableObject in your project folder . . .
Well, I'm too hooked on this stuff
On the left is an instance of a scriptable object type. It's probably an asset, much like a Material or a Prefab.
On the right is the script asset that defines a scriptable object type.
I coded flappy bird, next game will be mario
i know i didnt start just this week i started with the basics like 3 moths ago and didnt realy tuch unity unitll i understood somewhat the basics then i tried making a really simple 2D pong game without tutorial, and i made it with liltle help. now im making flapy bird also without tuorial and as little help as possiblle but i still dont understand stuff so i ask here for help or serch on the topic i am intersted and lean it and people give me some answers and i learn off that
that's pretty high. do you also have an insane drag value?
maybe super high mass too?
my lin damping is set to 0.92 and the auto mass is 0.82
Thank you guys
well something's not adding up then because that *should *be resulting in way too fast speeds
show me your current log
Can I 2d pixel art inside unity
What is the best ways for make Singletons ? i see several way to do.
In this video the guy put a [DefaultExecutionOrder (-10)] 🤔 https://youtu.be/Ol9yM21OvG0?si=RZESZEVAWO2wnE0W&t=95
the default execution order is a hack to prevent issues with accessing the singleton in Awake in other objects.
you recommand to do like that ?
no, i recommend not fucking with the script execution order if you can avoid it (you can). either initialize the singleton earlier than Awake, don't access it in Awake or OnEnable on other objects, or lazy load it.
here's my implementation of the singleton pattern that initializes before Awake (not that i ever actually access it in Awake on other objects anyway), and also lazy loads it if an instance doesn't exist
https://github.com/boxfriend/Utils/blob/master/com.boxfriend.utils/Runtime/Utils/SingletonBehaviour.cs
Don't do it; don't do it, I tell you . . .
Ok thank you
note that the implementation you showed was perfectly fine otherwise, and even can be fine if you aren't messing with the script execution order much else either. i just personally find that having to modify the script execution order to prevent errors caused by my own code is hacky
That class is the code needed for the scriptable object to be created from, it's not a scriptable object itself. What you have to do is right click in the assets folder, and in the dropdown menu you should see a "scriptable objects" option which will let you make the scriptable object itself
I wish to create ingredient in my restaurant game.
But I don't know how to approach the data structure of the ingredient, whether it's a class, a structure or scriptable object.
The main points of ingredient are :
- the ingredient has read only datas, and no methods.
- a new ingredient can be created on unity editor
- on unity editor, all Mono behaviour which properties contain an ingredient can be manually allocated an custom ingredient that I have created previously
ScriptableObject is probably a good fit
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
does anybody know why my masterVolume method doesnt work properly i attached it to my slider but when i drag my slider my audio for my music and sound effects turns off https://paste.ofcode.org/34e3xZPcEqz5vEWsuS3KkXE
why is it *= and not just =
i want it to be a percentage
so lets say if master is at 0.5 and sfx is at 0.5 multiply those you get 0.25 which is technically correct
did you debug the values or look in the inspector , what are the values set to ?
the values are between 0 and 1
But if it gets called multiple times it'll get multiplied to be smaller every time
1, 0.5, .25, .125
sounds like thats why it goes so quiet right away
ohh so how could i make it so that it doesnt reduce like that
have you looked into unity audiomixer it has a master slider already
the way that my thing is set up is so that it doesnt have to deal with all of that like dealing with audio mixers and making it so that you have to expose paramaters
idk what "all that" means
how do you want the values to go down exactly ?
if you want the percentage idk why you can't just use the values as is
0-1 I look at as percentage
i kinda want it to be so that it is like where if the sfx is 0.5 but the master is 1 it stays the same if that makes sense
private float masterVol = 0.5f;
private float sfxVol = 0.33f;
void SetVolume(float volume) {
master.volume = masterVol * volume;
sfx.volume = sfxVol * volume
} ``` on my phone so excuse the poor writing
like the master scales to 0.5 and you want sfx to be .25
ye was going to write similiar thing
sfxSource.volume = sfxVolume * masterVolume;
musicSource.volume = musicVolume * masterVolume;
this makes your life easier, not harder...
thank you i will try to implement this
You need to store the master volume in a variable and multiply all the other volumes by it when you set the master volume and when you set the other volumes . . .
(Also, while you're setting up the audio mixer, switch from "linear" to "squared" to get a volume slider that actually sounds linear)
unless it was "SquareRoot"; been a hot minute
and I'm using FMOD now so I removed my AudioMixer configurations
@pure drift The problem is when you set the SFX or music volume, it doesn't take into account the master volume . . .
im not sure how the code works i was wondering if you could explain it to me please
You’re making your life harder by not just using the built-in audio mixer system
I'm unsure why you're not using the audio mixer, it easily does all of this for you. If you connect/link your SFX and music volume mixers to the master audio mixer, it automatically scales the volume when the master volume is changed. You can even set up separate filters for each mixer . . .
ohh intresting ill keep that in mind
whats the best way to lear C# When i have almost never touched it before and dont know what 99.9% of stuff do in there and where should i but the stuff jk and watching tutorials is kinda slow and im probrably not gonna learn much from videos
start with the beginner c# courses pinned in this channel
thanks!
its gonna be hard because i dont even understand what some words mean :D
english is not my main language haha
do the intro to c# course on the microsoft site and set it to your preferred language
here you go! have at it . . .
Thanks you guys are real helpful!
i like those rb whitaker tutorials linked first, but his book is so much better
that's how i learned C#. i googled, went to his site, and read his tutorials. then i did the unity beginner and intermediate scripting tutorials; that was it. everything else was learned when i needed or found out about it . . .
because they are different
see, now there's a good question to ask . . .
because they happen at different points in the object's lifecycle
awake => initializations etc
start => reference access etc.
Awake is called before Start. Awake is called on disabled GameObjects, and Start is called when a GameObject first becomes active . . .
Awake and OnEnable are called immediately when an object is instantiated. Start is called later, which could be the same frame or the next frame. the only guarantee is that it will be called before any Update is.
typically you would use Awake for self-initialization and Start for reaching out to other objects
i see
pretty sure awake not called until gameobject is active , it does call if disabled script
ok yeah making sure I wasn't crazy
Awake is called even if the script is a disabled component of an active GameObject.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MonoBehaviour.Awake.html
yeah, this is what i was referring to to. i should've been more precise . . .
Oh okay! I was just about to go through all my scripts lol I could've sworn I read not long ago, I was having weird issues with awake not firing, didn't realize it was component can b disabled not gameobject 😅
apparently public methods called from other scripts do fire on disabled GO, so opted for a public Init() instead
well that makes sense. so long as you have a reference, you can access and call methods on any GameObject. being active only affects the Unity lifetime methods . . .
hah yeah assumed wrong that somehow unity was doing something special that might prevent that and maybe only setactive was something different but realize now its untouched
yep, a lot of my scripts have an Init method for setting them up. i just can't decide being using Init or Initialize. i have both and i need to figure out which one to stick with . . .
probably because i have Deinit and Deinitialize as well . . .
Yea feels much better controlling the events with init method, thats good idea should also have something to do that, maybe Disassemble lol
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i make my scripts pretty different from what is standard. i have a brain/controller script with the Update methods. all other scripts on this GameObject have an OnUpdate or OnUpdateXXX method. the brain references all the scripts and calls OnUpdate for them in their Update
when enabled or disabled, the brain adds/removes itself to the correct Update list on an UpdateDispatcher MonoBehaviour. this list holds all active GameObjects and iterates the list in its Update method
this allows me to separate and test systems or mechanics by simply enabling or disabling them to isolate an individual script . . .
ohh this is pretty interesting, seems like a good way to keep things flexible. Reminds me of something similar but used a custom tick for ingame time thing. I'm still experimenting trying to find a good system, still so much I'd like to learn in unity, but yeah also depends on the project requirements I suppose :p
very true. there are different patterns that can work. i'm deciding (or was until i forgot about it) to allow the child scripts (of the brain/controller) to search for the brain script and add themselves to an event. then, the brain would invoke this event in their Update method giving me the same functionality, but without needing to manually add a reference to each child script that is a part of the brain
i'd miss out on having control of the call order, but i can dynamically attach and remove each child-like functionality from the brain . . .
Yeah events are pretty nice, could maybe static event it ? Idk if its a good pattern but for me it works. I usually do that for registering / unregister OnEnable and OnDisable, this way the main script doesn't care about registering specific instances (I used to use arrays to loop through) it only receives that when child does some event it care about if any
@acoustic belfry What you call "voids" are actually methods/functions
Hi, how i can make that when an object interact with another, it activate the other objects methods
(from unity-talk)
oh, thanks
void is just a return type for a method/function
void aka dont return anything
i mean cuz i know how to make it interact...i guess
ah, makes sense
thats why the name
This example is still relevant ```cs
if(collision.transform.TryGetComponent(out PlayerComponent player))
{
player.DoThing();
}
DoThing is a method. You call the method with the ()
also, btw i have to get circle collider trigger on? Cuz i did a lot of other scrips (not made by me, just copy pasting tutorials, thats why im in here now, for make it from scratch) and none of them worked
now i have it turned on btw
ooh, nice
also, is there a way to modify the value of the state?
Use triggers if you don't want actual physical interaction but need to detect when things overlap
like, i make the player do thing, and also, i add a value, like, damage
what is a state
you can modify anything as long as its public
Non-triggers are for actually colliding with things
is just i came from GzDoom and everything is called a state, QwQ
You can call methods, you cant modify them at runtime
mmm...
then what i should do?
what does method do?
cuz what im seeking to do...and that i thought it would be easier for me QwQ but im dumb
Is,
Proyectile touches Player, player loses points on the int value health depending on the proyectile
pass specific values into it, change the state
and try to make it the most "by me" and simple possible
cuz obviously is better to know what you wrote than just copy pasting
it technically takes points from the health value
depending technically on the proyectile
store projectile damage amount in the projectile script, when you access the health component you can pass whatever value you want to subtract damage
You can add a TakeDamage (you can name it whatever you want) method to the player. It could take an integer/float value as a damage parameter
So you'd make a function on the player that loses health, then call that function in on collision or on trigger
i mean, i know what to do, my issue is, how to write it
with code
thats technically always my issue with this kind of stuff
Tbh since you didn't know what void means or what methods are called, I feel like you have skipped the basics
Of C#
yeah that is part of the reason its diffcult to write it
you have to know the basics of c#
On collision and on trigger give you the object you collided with as a parameter. Get the player component from it and call the function on it
unity has an API function for each thing you need, just need to know how to read that api (knowing c# basics)
also Osmal literally wrote the code example for you
#💻┃code-beginner message
vsc not recognizing PlayerMovement as a component???
