#💻┃code-beginner
1 messages · Page 304 of 1
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
How can i use this if statement to find if int waterDrank has ever been as high as int itemPrice?
public class DiscoverItemLogic : MonoBehaviour
{
public int waterDrank;
public int itemPrice;
// Start is called before the first frame update
void Start()
{
}
void isRichEnough(bool richEnough){
}
// Update is called once per frame
void Update()
{
if(waterDrank)
{
}
}
}
if (waterDrank >= itemPrice)
You mean like
if (_waterDrank == _itemPrice
{
// Code
}
simple equality check
You can either check if it is the same value == or if it is the same or more with >=
Well, then do it in a single message
my bad hold on
Update is not called infinitely, so there might be a situation when the waterDrank has surpassed the itemPrice
im using the if statement to enable the item after the user gets enough cash, but If it only checks for when waterdrank is >= itemprice, wont the item dissapear after their cash goes lower
Something like
so for example if it costs 1000, the user unlocks it, but then they spend and their money goes back to 200 for example, wont the item disable?
why is it in update in the first place
Well they asked to check if it ever was as high as item price (==)
to check if the user has enough at all times
there is no need tough, you just check when attempting to make purchase
once you purchased, store it in the inventory
there is no way they can disable it if you already own it
No, it shouldn't be in the Update. It is much better to check in the method the cash is being updated
Guess that's not what they wanted in this case tho
I want this to only be shown once they have enough cash basically
Alright, checking it in the Update is wrong anyway
then never dissapear after
you could have a bool unlocked, which is made true when waterDrank gets higher than itemPrice
You should have events each time the money updates, if it passes threshold show the button
once amount is lowered, you update ui accordinly
Yeah I rarely use update. I either check something every now and then with an IEnumerator or just invoke an event Action when the values changes
Oh alright ill look up how to set up events then
cause im not sure what you mean by that fully
thanks
Yes, Update should never be used in this case
Agreed
this one is good too, you can probably just use the Action<int> type
https://gamedevbeginner.com/events-and-delegates-in-unity/
public static event Action<int> OnMoneyUpdated;
for example
how do i make a cinemachine virtual camera rotate with your mouse like a freelook camera?
the same way you rotate regular cam
ik but i need to use a virtual cam
wdym
The started, performed and canceled actions are called when the input is started, changed while being held or canceled respectively.
If you have an action of type Value with the control type Axis, the started and performed actions will be called simultaneously just once when the action is triggered.
E.g. pressing the Space button on the Value Axis action looks the following way
started
performed
... the button is released
canceled
In your case, neither making the player fly, nor changing the global value and then using it in the Update in the method subscribed to the performed action won't work.
For your flying logic I'd suggest first unsubscribing your Fly method from performed and instead performing the logic in the FixedUpdate.
Get the flight direction by reading the float value of the Value Axis action and apply the continuous force to the Rigidbody considering its mass using the default ForceMode.Force.
private void FixedUpdate()
{
float flyDir = _flyAction.ReadValue<float>();
if (flyDir != 0)
_rigidbody.AddForce(flyDir * flySpeed * 100f * Time.fixedDeltaTime * Vector3.up);
}
you mean like rotate around object?
You want to rotate it from a POV or around an object?
im tryna make over the shoulder cam and i want to rotate around player
so use freelook?
Add extension offset to pov cam and you get this
is that freelook
the CinemachineFreeLookCamera is a virtual camera
it's just one specfically designed for 3rd person camera controls
ok
Like this?
ye but with shoulder offset
what is "shoulder offset" mean
this is offset
like camera to the right a lil
the camera follow is my eye
that just a freelook no?
No this is pov
oh
you probably want the Third Person mode on body then
yes i have that
but camera doesnt rotatd
you'd have to manually do it via code in that case
with rotatearound?
look at the Unity third person controller demo, it has that
yeah. It's code you can do almost anything with code
forgot how they do it
wow thanks for the enlightenment
You asked xd
🍿
In the end I just put a boolean "is flying = true" when performed and "is flying = false" when canceled
Then put an if logic that propels the rigidbody upwards in fixed update
apparently is this
private void CameraRotation()
{
// if there is an input and camera position is not fixed
if (_input.look.sqrMagnitude >= _threshold && !LockCameraPosition)
{
//Don't multiply mouse input by Time.deltaTime;
float deltaTimeMultiplier = IsCurrentDeviceMouse ? 1.0f : Time.deltaTime;
_cinemachineTargetYaw += _input.look.x * deltaTimeMultiplier;
_cinemachineTargetPitch += _input.look.y * deltaTimeMultiplier;
}
// clamp our rotations so our values are limited 360 degrees
_cinemachineTargetYaw = ClampAngle(_cinemachineTargetYaw, float.MinValue, float.MaxValue);
_cinemachineTargetPitch = ClampAngle(_cinemachineTargetPitch, BottomClamp, TopClamp);
// Cinemachine will follow this target
CinemachineCameraTarget.transform.rotation = Quaternion.Euler(_cinemachineTargetPitch + CameraAngleOverride,
_cinemachineTargetYaw, 0.0f);
}```
whats _input.move
see edit that was character, this is camera
thx
That's more logic and might be a bit redundant. Additionally, as I have mentioned in my previous response, if you want to use the logic with enabling and disabling flying, consider setting it to true when started, not performed.
hi i have a current turn int on my battle manager but in my other script i cant get access to it. dont understand why
Cannot resolve symbol 'currentTurn'
What is the exact error you get?
It's trying to search that variable on this script, not on the manager
you know how to reference canBlock. Why would currentTurn be any different?
in my battle manager under active battlers it returns if the current turn is an enemy or a player
thats right why is it different
i dont get it
Yes and there it can get it because you're already in BattleManager
But outside of that class, you must refer to it like usual
why are you trying to do it differently?
sorry im lost can you see where im doing it differently?
When you open a [] it doesn't magically switch the context into the other class
You're not doing it differenly, that's what the problem is
even if im calling it on a instance?
Yes
i see
You can only pass parameters from the calling class
Here
both variables are on the same script so you need to access them the same way
BattleManager.instance.activeBattlers[BattleManager.instance.currentTurn].isEnemy) {
thank you
How can i make like a global static variable that i can access from anywhere?
like i want this specific array of 4 colors that i dont want to keep readding into my scripts
have a static class with a static variable
where do i change those variables though?
You can just do something like this
public static class Information
{
public static Color[] MyColors =
{
// Colors
};
}
(correct me if I'm wrong)
You could also have a class with singleton reference have a public variable, which you then access through an instance of said class
Can you define array like that?
Yea
Didn't know that
i'll just do your first implementation, thank you! i need to find the rgba values for the colors i need now though
it is collection initializer syntax
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers#collection-initializers
That's quick to find on google or in the inspector, depending on what colors you need
yeah, its just annoying how in unity its between 0 and 1 instead of 0 and 255 like all other color generators
I think you can choose different approaches no?
from the docs it looks like its strictly 0 to 1
huh
Color32
That is between 0 and 255
Color32[]
This is from the base map color of a material
either way, i found a website that does 0 - 1 calculations
Yeah depends on how you implement it in the end
Converting from 0-255 to 0-1 is as easy as dividing all values by 255
can someone help with Physics.CapsuleCast? it will only occasionaly detect (1 out of 100 times or smthing) objects.
check out #854851968446365696 on how post questions and what to include
ok, thx. One sec. (i can post the question here right, i couldn't find if there was a particular channel for help)
It's about coding so yeah
ok, so i got a problem with a capsule cast. If I Debug.Log(); it it will nearly only put out true's and only occasionaly a false. This seems to happen on spesific points but i dont know why. Is something wrong with the code?: (one sec typing it in with the ! code thingy)
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oops, bit too big
Yeah or like this
You want to make the player move when the capsuleCast is NOT colliding?
when it is not colliding the player should be able to move yea
Okay
So the problem is, that it is colliding when you dont want it to?
If the player has a collider attached, it may collide with the players collider. Try using a layermask
no, it isnt colliding most times. it nearly always says there is no collision even when i am going to the other gameobjects
i will try for a sec
Are you casting it from the bottom of the player or the middle of the player?
You should put in a Debug.DrawRay to check the direction and distance of the cast, make sure it goes where you want it to
is there a from the bottom or top with capsulecast? i thought it was the whole thing (but i dont know that much so educate me please if i am wrong)
ok, 1 sec
You wrote transform.position as the origin, meaning at the position of the gameObject the script is component of
All these positions are based on pivots. The pivot (and thus transform.position) of a capsule is the center if it is not changed. The pivot of the capsule cast should also be the center iirc
However, if you are casting from an empty and the capsule is a child, it may be going from the ground/feet
Ah mb I thought about sphere cast
o, ok
i do unfortunately need the capsule on the moment
i am casting from a empty
Found this showcase of casts, may help. Bcs I can't help you otherwise rn sorry
https://www.youtube.com/watch?v=fJyi7l2tWKo
i already looked at that one, but thanks still
Oh okay
Well I assume you made a mistake somewhere in the cast, but idk what you want to achieve and where stuff has to be
Probably fastest if you trouble shoot it yourself
Then it may he going along the ground. This would be colliding with the ground of course, making it so you can't move
I think a layermask was suggested earlier? That could help
Yup
the thing is that it isnt colliding at all. i am falling trough the floor and if i go up it still doesnt collide
Try simulating the problem in a test scene
Ah, hmmmm. Does the empty gameobject have a collider?
just for a sanity check, is your game 3d?
yes
yes
already doing it
but the movement i only in 2 directions
or 4 depends how you look at it
Aslong as you are using 3D Colliders..
i am
there can be a lot of issues here, like if the cast is starting inside an object. in 3d the cast wont hit something it starts inside. You can use Debug.DrawRay to visualize stuff, vertx also has this https://github.com/vertxxyz/Vertx.Debugging to visualize casts.
I think your first 2 points are wrong though
Physics.CapsuleCast(transform.position, transform.position + Vector3.up * playerheight
because playerheight is somewhat a random number here.
Plus you are also moving the transform before the cast, you arent using canMove anywhere in the moving logic
ok, thx. i will look into that
Hi, I am currently trying to put a pink icon on a gameobject so I can see it, but I still cannot. May someone help?
Thanks for the help
Np, great website
Hey guys, how can i reference an integer from another script? In one of my scripts I need to reference an integer created in another.
it should be a public variable
you dont need to make it public, often times it is bad to. Public means any script at all can change this value to anything they like, even if it makes no sense in context.
Design wise, its better if you have a property or method which returns the int as a value
Oh alright.. So how can I create a method to do this which I can call in other scripts too?
the method can be public, that is fine. This website is a decent resource https://www.w3schools.com/cs/cs_methods.php
a method has
[access modifier] [return type] Name
You need a reference to the script you want to call the method on
i strongly suggest doing c# outside of unity first. learning stuff like this can be done way faster especially if you arent trying to deal with unity bugs at the same time. plus unity will take way longer to compile
https://hatebin.com/hbfqtheqnz Hi, I have a problem with animations, the problem being that the "UI(popup)" animation plays out on starting the scene but then doesnt play again when the racast is in a collision with a gameObject that has the layer Interactable.
oh couldnt it be just that the animation is called over and over again?
just tested it out and can (MABY) confirm that that was not the case
Hey guys, I have a game manager script that is persistent. How can I make sure the references between levels (unity events) are not lost?
So to get it straight, it plays once when the scene starts then not again after?
ehm, yes sir
Delete the first log and keep the one inside the LayerMask if statemen then tell me if it still logs everytime
I know you're aware but the two Debug.Log lines are the same, so it's confusing. It may be logging the collision of the raycast but not the LayerMask part
its registering
So your issue is a visual one related to the Animator?
hmm I gues you are right
cuz setting the animation on loop works
Then if that log is correct, it has fired the animation 376 times
I resolved that already wait a moment
I am stomped to be honest
With the new script you sent, when does the Debug.Log fire?
Is it whenever a new object in that LayerMask enters?
Sort of like KeyDown
I spams the console with the name of that object when I am looking at it
it
if that helps lol 😄
So yea, it my understanding it is still firing the animation every frame when your object is colliding with the LayerMask
That bool check is not working and I don't believe it is a good way to check
There is an old legacy method called Animation.IsPlaying which would check if the animation finished or not
and couldnt it be that this script is on another gameObject that the animator?
its theonly thing that comes to my mind now to be fair
But you shouldn't use it, instead you can do:
- Based on time. Do a timer that gets the animation length in seconds (this is ideal)
- Use a key frame event at the end of the animation that sets your bool isPlaying to false (unreliable)
- Apparently
Animator.GetCurrentAnimatorStateInforeplaces the old legacy method. Here
how do i make a gameObject move forward along the x and y axes based on it's z rotation in a 2d game?
ok I will look into it thx 👍
Well all I can see is that bool check is not at all reliable. You should change it because you'll need to eventually anyway when handling many different animations
For the timer you can use coroutines, then it gets the animation length, waits until finished then sets the isPlaying bool to false.
I do really think it is the bool playing up
ye, I dont really know how coroutines work so I look into unitys API then, much appreciated
how to move a gameObject move forward in 2d?
i have a bullet script and even though i am trying to make it dissapear when colliding with an object it just phases through. ill link code here: https://gdl.space/tuqulugoqu.cs
what I see is on CollisionEnter, which means one of your gameObjects needs to be isTrigger if I am not mistaken
can it be any of them
ye, prefarably the bullet tho
not working. Any tips?
show me your bullet in the scene with inspector
bullet on the right
ok hold on for a minut I will try smth
ok
ye, so you do have a rigid body attached to the bullet right?
no i dont it lags my game
oh well you need it look https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html
it explecetly says there needs to be a rigidbody attached to either of these objects
turn off the isTrigger
kk
So i have a bunch of slots that may increase and decrease over time in my game, is there a way of adding the Slot's gameobject dynamically? (via code in the second screenshot)
still broken
you need to move the bullet via the rigidbody i think
ill try that
when I was making a bullet what I did was get an enemy with non-kinematic rigid body and collider then I made a bullet that had collider that was set to is trigger which worked.
i tried to make it move by rigidbody and it collides every now and again but the others just phase
show how your moving it, and are all the objects your trying to hit setup the same way
try using AddForce with an Impulse
trying now
In C#, can I forgo event signatures if I don't need them?
public void SubscribeToServices()
{
// is not interested in the current and max turn number
TurnService.Instance.OnTurnStart += SimulateSpaceshipMovementForAll;
}
// is forced to define the signature -> quite bloaty
private void SimulateSpaceshipMovementForAll(int currentTurn, int maxTurn)
{
/ ...
}
its still broken however some of them collide and bounce off
No, a handler must conform to the delegate type of the event it's being subscribed to
You can add a lambda in between, but you lose the ability to unsubscribe from the event.
+= (_, _) => YourMethod();
Make sure the collision mode is set to continuous
trying now
Yeah I need to unsubscribe. But thanks !
omg it works tysm
can someone help my intellisense isn't working for unity its not coloring the words at all
my package is installed on visual studio for unity
can someone help me with the destroying of my bullet? code is here:
What's wrong
its not destroying the bullet
Is it a 2d game?
nope 3d
Does it have a collider
Do you have either whatever the bullets colliding with or the bullet set to isTrigger?
yes colliders on bullet and a rigidbody
no
Well, you can’t use on trigger enter if one of them isn’t set to isTrigger
Use on collision enter
alr
i downloaded the EZ Camera Shake asset but i cant add the script thats in the video? like its not popping up in the "add componant" for me even though it is in the video
i wish I could figure out when I create a script it doesn't color any words other than the typical words built into c#
doesnt work
Show code
hold on im trying somethiong that might
hello complete beginner here! i am currently following a tutorial for crouching and sprinting in my 3d game. all the code is working and the button mapping is working but for some reason the actual crouching and sprinting in game doesnt work. please help and lmk if you need to see my code or the tutuorial im using. Thanks!
It takes a bit of a different setup. You can't just change the name from OnTriggerEnter to OnCollisionEnter
The parameter also needs to change
ok so visual studio 2022 works with intellisense is there any reason to use 2019 instead of 22 if Im using version unity 2021?
how?
Takes Collision, not Collider
in "add component" its supposed to say EZ Camera Shaker and then show a script for me to add, but its not showing either of those
no
When someone suggests something, step number one is ALWAYS to google the docs
ok got it
just to clarify when i said the code is working, i meant there are no errors
will this work?
if that doesn't work, then consult this: https://unity.huh.how/physics-messages
pls somone help
Post your code
see #854851968446365696 for what to include when asking for help
My time has come. I’ve put this off as long as I can, but there’s nothing else left to do. I have to shudders learn how to use text mesh pro.
Try again
wdym
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
oh ok
it says my code is too long to send as a message
i think i found the problem tho
Read the pop up
bruh can someone help me
i cant figure out whats wrong
You’re ide might be configured wrong
#💻┃code-beginner message
Yeah, do not just drag the file in or copy it in
See the "large code blocks" section
sry i joined discord literally 5 min ago
No worries
Do you have the right package installed
Because EZ Shaker isn't something in the base unity
'Rigidbody' does not contain a definition for 'enabled' and no accessible extension method 'enabled' accepting a first argument of type 'Rigidbody' could be found (are you missing a using directive or an assembly reference?)
im on unity 2022
anyone?
Rigidbodies cannot be disabled
they used to
Not that I ever remember
so just set it kinematic?
i downloaded it, opened it, then clicked import
im prolly missing something aloong the way
If that's what you're going for. Can't answer without details
incorrect. Rigidbody does not inherit from Behaviour, it inherits directly from Component which does not have an enabled property
"It" ?
oh alright
i swear i remember being able to disable them
I love that movie
i downloaded EZ Camera Shake
Ok, do you see the folder in your project window?
yes
What is a good way to orgnaise my levels? Right now I have a GameManager is in DoNotDestroyOnLoad, I use functions like GameManager.LoadScene(string sceneName) for serialisation. But the issue I've ran into is now the references are lost when the scene changes
Find the script you want and just drag it on instead of looking through add component
: (
if i set a rigidbody to kinematic does that already reset the velocity when i enable it?
make sure you have no compile errors
Generally, I use a DontDestroyOnLoad singleton game manager to handle switching between scenes and things that generally apply to the whole game, then a scene manager in the scene its managing to handle anything in-level
It varies game to game though
it probably depends on the type of rigidbody. for a 3d rigidbody kinematic bodies don't use the velocity so i would assume that it resets velocity to 0, but you'd have to double check. 2d rigidbodies actually do utilize velocity so i doubt it would reset it on that
Yes, I went this route too, but now when I want to reference it let's say in level1 it already exists in the mainmenu level. So I lose the reference, makes sense?
Wait I will paste what I said earlier because I know that might be vague
So let's say my GameManager handles a method called LoadScene(string sceneName)
I use unity events so when the player from the main menu clicks "Play Game", it fires LoadScene("Level1")
Okay so it does exactly that woohoo. But then it gets to Level1 and the player wants to return to the menu. GameManager, which is persistent, cannot be referenced on the "Back to menu" button because it didn't exist already in that level, only MainMenu.
I can reference the level objects in static fields. But the issue is they are not serialized and that's really what I am aiming for.
The reason a method like GameManager.LoadScene(string sceneName) exists is again, due to serialisation
Don’t make the GameManager handle the main menu, make a main menu scene manager
So each scene should have a GameManager of its own?
Each scene should have its own scene manager that handles anything that only applies to its own scene
Does that make sense?
Yes, but what about general methods like LoadScene and scene transitions?
There are a couple ways to do it. You could make the scene manager switch scenes, or make the scene manager call a method in the game manager that switches scenes
Hm, I see. Thank you noodle
Ofc
I like to leave the "game manager" in charge of scene transitions
It often needs to run code before and after a scene change, so it just makes sense
My character starts with a y value of the transform to be 0.03, but as soon as I start walking it bumps up to 0.08
I am making sure moveDirection.y = 0, before updating the position
Could there be an issue with the animation. root motion is off
Yeah, or you can make it like a fsm and make the first scene have some code that runs before it switches scenes and have the second scene have some code that runs on Start()
How I'll try it if you are interested is
SceneManager.LoadScene goes inside MainMenu.PlayGame
I think it just depends tbh
That's the thing too, I have an FSM
I use a big coroutine when doing scene transitions
the FSM runs code before and after the scene is loaded
The coroutine itself is responsible for fading out, triggering the scene load, and fading back in
For example, pausing the game
Then it runs another coroutine based on which scene is being loaded
so entering a game scene causes it to run a "start game" coroutine
why when i sometimes drop the item, the position doesnt get set to the drop position?
hi im new to coding and i need help with a 2d project i have tried youtube tutorials but you need specific code that i have done a different way and i dont know what to do the thing that i am trying to do is make wall jumping in a simple little platformer i have made movement using youtube tutorials but there is nothing for the code i used and am unsure on where to go please help
which yells at the scenario controller, which yells at all of my other controllers and then starts the game
u can see when i dropped the last item the position didnt get set to the drop position?
and this is random
cause i then picked it up and dropped it again and it worked properly
i would add some bright glowing material to highlight where dropPosition is while playing
i debugged it
and it does get set to the drop position
but instantly gets set back
to its original position
or some other position
the position is also random
i checked through every script and nothing is manipulating the position
It has to be some script doing it. Try attaching the debugger and going line by line if you can recreate it
wdym the debugger
visual studio debugger, it will pause execution and you can play line by line
im using vs code
unlucky
I got bored at 1003 ngl. Also might be better to ask in #💻┃unity-talk or post a thread in #1157336089242112090
You'll get a better response I think
I would try recreating this issue in a barebones environment, no scripts anywhere else. With the minimum amount of scripts present, you can try following through whats happening. Add a lot of debugs around
Although the debugger would really make this easier
whoever wrote this question has their priorities in the wrong places. maybe you're better off not joining that club 😛
weird rephrasing of your math homework
isn't this pretty much just asking if every power of 13 is coprime with 1003
oh god i'm getting nerd sniped here
this has nothing to do with unity and also nothing to do with programming in unity, so...
Yea, like I said yeah, you should ask somewhere else yea. People may know yea but you wont get a great response here yea
also you're in the programming server, I'd ask there
yes
i found the issue
So i downloaded a weapon asset pack and the weapons are prefabs, how do i make them not perfabs
but i still dont understand
Well time to move on and make your own bigger, better gaming club. It's a math question, written extremely poorly imo, probably by a student who wants to act smart.
Dont waste your time on silly things like this, you'll NEVER need to do this for a game. Start your own project and have fun 🙂
could u help me understand why this has an affect? @eternal needle
i set the interpolate on the items
to none
and suddenly it works
yeah
Interpolate causes the Rigidbody to set the position of the transform every frame
item.transform.position = dropPosition.position;
this will clobber the position you set
you need to set the position on the rigidbody itself
this will tell it to move there in the next physics update
oh
Why would you not want them to be prefabs?
With interpolation disabled, the rigidbody will see the new position in the next physics update, and it'll..mostly work
nvm im being stupid
so how do i set the position of the rigidbody?
item.rb.position = dropPosition.position;
like that?
😅 well time to check some of my code because i didnt know that was a thing either
If you really want the object to move instantly, set both its position and tell the rigidbody to move, I guess
but the rigidbody will still wind up overwriting the position
setting Rigidbody.position just queues up a movement for the next physics update
i think i need to
u can see it kind of teleport
cause im just doing item.rb.position = dropPosition.position;
would this be fine?
alright it works
does anyone know what this means and if i can make it work trying to add pits to some free code im adapting to my game, pretty new to c# and been trying to research this for like 40 mins now still lost
cell refers to this for clarity
Make sure that is the correct Cell type
If you hover over Cell where it cause issue, you should see the full type signature.
Also, configure your!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
• Other/None
so im pretty bad at coding, is there a way to make a code that says to set an object as a child of another object with the click of a key?
Sure. There's almost nothing you can't do with code.
Break it down:
- input query
- check the input
- parent object a to object b
Then you should go over the basics. Unity !learn beginner pathways is a good way to start.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ive actually started the create with code course
i just never finished it
i tend to lean towards the more artist side of things
But to answer your question, you can use the Input class to query input. And parenting is handled via the object's Transform component. The API of both of them you can find in the API docs.
alr, thank you
alright so that worked but is there a way to set the child to a certain position then when its picked up? because right now it just attaches to the parent from its current position, and i want it to be closer, like a flashlight would be
you can set its localPosition relative to the parent
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class pipepositions : MonoBehaviour
{
public float upperExtreme = 3.19f;
public float lowerExtreme = -3.68f;
public GameObject PipePair;
private float timer = 0.0f;
private int spawnInterval = 2;
// Start is called before the first frame update
void Start()
{
}
void Update()
{
Vector2 moveLeft = transform.position;
timer += Time.deltaTime;
Debug.Log(timer);
if (timer >= spawnInterval)
{
SpawnItem();
timer -= spawnInterval;
}
}
void SpawnItem()
{
Instantiate(PipePair, new Vector3(1.8f, -5, -0.2f), transform.rotation);
}
}
System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LeftMove : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector2.left* Time.deltaTime * 10);
}
}
Ok so I have these scripts, making a crappy_bird game ( I literally call it crappy bird )
problem is I have these pipes but they're not moving to the left
I have this one right here outside of the camera
and It is cloning them
but the clones literally get spawned into the middle of the screen like this
Also this script you see called pipe position is in the Pipe Holder Object because otherwise it will create exponential duplicates through the instantiate method
hey so in my script that deals with saving and loading https://hatebin.com/afndomhsfy something in their is causing it to not load right and it just infinitly loops and doesnt load the scene can anyone help me please
Having an issue that I just can't wrap my head around. So, I have this rigidbody controller, and moving around works perfectly, except for when I start looking towards the ground. The game seems to lag a lot, and unity just doesn't seem to know what direction I'm looking in? Give me a second to send the code here, I'm sending this from my phone
what did u use to film this? looks so smooth
here's the player controller, i used one of my old controller scripts as a reference, and it always worked just fine with normal unity input
samsung screen recorder
looking at the floor also lags the game out for whatever reason
can you also share the static SaveSystem class
i wonder how often ur Save() method is being called..
setting either one of these to anything different causes it to lag, badly
just the input
the only thing I can think of is maybe ur player is triggering the collision over and over? idk i'd debug the OnTriggerEnter2D better to see whats happening to make suer it wasn't
it gets called only once when you enter a save point
So Im coding rn, and I got an error which said something about protection level not being available. So I set the private thing to public and the error went away, but now in unity when i try to playtest it says theres an error about the same thing and when I go to fix it, visual studio says theres no error. What do I do
- your !ide is not 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
• Other/None
- you need to show the exact errors
Start from sharing more details
- the error will show the script name and line numbers, show that code
the error exactly: "Assets\Scripts\Player\PlayerInteract.cs(36,33): error CS0122: 'InputManager.onFoot' is inaccessible due to its protection level"
i did find when loading it from the main menu even though it works fine i get this error it doesnt seem to affect anything
Cannot load scene: Invalid scene name (empty string) and invalid build index -1
UnityEngine.SceneManagement.SceneManager:LoadScene (string)
GameHandler:Load () (at Assets/GameHandler.cs:62)
GameHandler:Start () (at Assets/GameHandler.cs:19)
but in visual studio theres no error
off the top of my head i was thinking this..
your player triggers a save
then a new save is made
if the new save triggers a load i could see maybe a loop or something happening
As I just told you, that is because your ide is not configured
i have no idea what that means
but if the Save function doesn't itself cause a Load function to go off.. im not sure what is the issue.. im just overlooking it i guess
Read the bot and follow the steps
which bot
ok
it does not the only way a load function gets called is when you start the scene
ya, thats why im confused.. cuz thats not the case
oh wait hold on i think i might know why
wait that bot is just a picture
yay! talking it out always helps
!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
• Other/None
oh i got it
the one above it isn't
if every time the scene is loaded it loads the scene then it probably is stuck in a loop
make sure to follow those steps accurately..
although im not sure why it doesnt do it when its loaded from the main menu though
can i do this in safe mode
people have a tendency to fly thru them.. and not get anywhere.. b/c if it doesn't work the first time.. the only step is to repeat it
i doubt it..
will my game corrupt if i exit safe mode
if (saveObject.currentSceneName != SceneManager.GetActiveScene().name)
{
SceneManager.LoadScene(saveObject.currentSceneName);
}
this should make sure that the current scene isnt the one to load correct
No
also doubt it.. if it opened the first time it'll open the 2nd time
Safe mode is just faster to open because it doesn't load everything
Easier to fix the errors quickly and reload the rest after
game didnt corrupt lets go
learn to use Github / Version Control..
until then.. Start to use local backups when u get to a good checkpoint
i cant find visual studio in my files but i can open it from the unity editor
should i just (re?)download it
ye
this isn't ran in an Update loop or something? is it..
nah just before it loads the scene
Common7 is in program files, microsoft visual studio
Or program files x86. Can't remember
i searched in my pc and nothing showed up
Did you just look where I am saying?
ill try again
i dont see it in either
i looked in program files and program files 86
if u can get it open just go to
then click System Info >
itlll show u where its installed
For Microsoft Visual Studio?
If you don't see it- ah, spawn was fast. Nice
ok thanks
just so happens to be a VS day and not a VSCode day 🙂
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class pipepositions : MonoBehaviour
{
public float upperExtreme = 3.19f;
public float lowerExtreme = -3.68f;
public GameObject PipePair;
private float spawnTimer = 0.0f;
private int spawnInterval = 2;
public void DestroyClone()
{
// Replace "cloneObject" with the actual reference to your clone GameObject
}
// Start is called before the first frame update
void Start()
{
}
void Update()
{
Vector2 moveLeft = transform.position;
spawnTimer += Time.deltaTime;
Debug.Log(spawnTimer);
if (spawnTimer >= spawnInterval)
{
SpawnAndDestroyClone();
spawnTimer -= spawnInterval;
}
}
public void SpawnAndDestroyClone()
{
string cloneName = "Matrix_SuperPipe_600";
Instantiate(PipePair, new Vector3(7.73f, -2.85f, 0), transform.rotation);
PipePair.name = cloneName;
StartCoroutine(DestroyAfterDelay(PipePair)); // Start coroutine for delayed destruction
}
private float destroyDelay = 10f;
private float destroyTimer = 0.0f;
IEnumerator DestroyAfterDelay(GameObject cloneToDestroy)
{
destroyTimer += Time.deltaTime;
yield return new WaitForSeconds(destroyDelay); // Wait for specified delay
if (destroyTimer >= destroyDelay)
{
Destroy(cloneToDestroy);
destroyDelay -= spawnInterval;
}
}
}
What is wrong with my code not destroying clone objects after a while?
You are adding deltaTime every 10 seconds.
Then just checking if it's over the timer
deltaTime is a tiny number like .02. So it's gonna take FOREVER. And that's only if you call it over and over to actually increase the timer, because this is not a loop
Why not just do waitforseconds and destroy it? Why the other timer and if statement?
should i?
A couple of ways to configure Visual Studio and Unity.
- You already have Visual Studio : 0:25
- You need to download Visual Studio,
- through the Unity Hub : 2:09
- through Visual Studio's Homepage : 2:49
Visual Studio Download Page :
https://visualstudio.microsoft.com/downloads/
thanks
heres a video i made.. i timestamped it at a place where u can isntall the Plugin from within the Visual Studio
that way u dont have to hunt down the Directory its stored.. altho u still will need to assign it inside Unity's Preferences
is there a method for that?
For what?
its normally used in a Coroutine
You are literally using it
Already
JUST remove your if statement
IEnumerator DestroyAfterDelay(GameObject cloneToDestroy)
{
yield return new WaitForSeconds(destroyDelay); // Wait for specified delay
Destroy(cloneToDestroy);
destroyDelay -= spawnInterval;
}
}
void DestroyObjectDelayed()
{
// Kills the game object in 5 seconds after loading the object
Destroy(gameObject, 5);
}``` also fun fact, Destroy() has a parameter u can use to delay when it gets destroyed
good for use when its a more simple setup
does that i mean i dont have to use the other methods?
i dont see u using the coroutine for anything other than destroying it after a delay.. so i guess u could use it for that
@rocky canyon@summer stump thank you so much for your patience. I just started game development last night and I know nothing. Im starting to pick stuff up but if it werent for you I would have never fixed my problem
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class pipepositions : MonoBehaviour
{
public float upperExtreme = 3.19f;
public float lowerExtreme = -3.68f;
public GameObject PipePair;
private float spawnTimer = 0.0f;
private int spawnInterval = 2;
public void DestroyClone()
{
// Replace "cloneObject" with the actual reference to your clone GameObject
}
// Start is called before the first frame update
void Start()
{
}
void Update()
{
Vector2 moveLeft = transform.position;
spawnTimer += Time.deltaTime;
Debug.Log(spawnTimer);
if (spawnTimer >= spawnInterval)
{
SpawnAndDestroyClone();
spawnTimer -= spawnInterval;
}
}
public void SpawnAndDestroyClone()
{
string cloneName = "Matrix_SuperPipe_600";
Instantiate(PipePair, new Vector3(7.73f, -2.85f, 0), transform.rotation);
PipePair.name = cloneName;
StartCoroutine(DestroyAfterDelay(PipePair)); // Start coroutine for delayed destruction
}
IEnumerator DestroyAfterDelay(GameObject cloneToDestroy)
{
yield return new WaitForSeconds(5); // Wait for specified delay
Destroy(cloneToDestroy, 5);
}
}
why does my code stop spawning pipes after a while?
no worries.. it takes time.. u learn by doing.. trial and error is the best method to learn imo
ye Im learning about that stuff in my engineering class
👀 well lets hope engineers do trial and error on small scale stuff first 🤣
hopefully they arent just throwing up bridges im driving over.. that they're using trial and error on
Why are you combining the coroutine and what spawn said?
nah bro ur good
at least from me
ohh electrical engineering 😄
lol
lmao facts
@whole idol Ah, you passed PipePair into your destroy method
You need to cached the object from the Instantiate call and destroy THAT
You should be getting errors when it stops spawning, right?
pipesJustSpawned = Instantiate(prefab...); Destroy(pipesJustSpawned);
wanna destroy the pipes u just created.. not the prefab ur creating them from
nope, didnt get any errors
ok so i made an entire new script cause it was getting too long and a headache to share and read so I made this and attached it to my new pipes and parent pipe object holders
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyerScript : MonoBehaviour
{
public GameObject pipeToDestroy;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
SpawnAndDestroyClone();
}
public void SpawnAndDestroyClone()
{
string cloneName = "Matrix_SuperPipe_600";
GameObject clone = Instantiate(pipeToDestroy, new Vector3(7.73f, -2.85f, 0), transform.rotation) as GameObject; // Store the instantiated object
clone.name = cloneName;
StartCoroutine(DestroyAfterDelay(clone)); // Start coroutine with the clone reference
}
IEnumerator DestroyAfterDelay(GameObject cloneToDestroy)
{
yield return new WaitForSeconds(5); // Wait for specified delay
Destroy(cloneToDestroy); // Destroy the clone after the delay
}
}
Alright. Does it have an issue?
wow I just almost crashed my computer
I didn't expect any problems out of this but somehow instead of destroying objects this started creating exponentially millions of objects in merely a few seconds filling up my screen with pipes and clones
lol
For organizing a unity project, does it make sense to group the models and animations with the scripts. like putting everything in assets/zombie/ ?
ur not developing if u dont almost crash ur computer from time to time
or should I make an effort to separate the scripts from the models and such
it just depends on how u wanna sort things..
this is a common debate
i've developed for a while, but new to game dev. does game dev favor the functional vs domain organization compared to what i've done before (web app dev)?
say I have variable A and variable B, both of the same type, myClass. If I assign variable A to an instance of myClass, then I assign variable B to variable A, then I reassign variableA to a difference instance of myClass, will variable B also now point to this different instance of myClass?
is it Scripts, Prefabs, Models with a Truck folder in each one
or is it Truck folder with Scripts, Prefabs, and Models folder in each one
in web dev you can organize either way, thought it might be a bit different organizationally with all the game assets.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyerScript : MonoBehaviour
{
public GameObject pipeToDestroy;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
SpawnAndDestroyClone();
}
public void SpawnAndDestroyClone()
{
string cloneName = "Matrix_SuperPipe_600";
GameObject clone = Instantiate(pipeToDestroy, new Vector3(7.73f, -2.85f, 0), transform.rotation) as GameObject; // Store the instantiated object
clone.name = cloneName;
StartCoroutine(DestroyAfterDelay(clone)); // Start coroutine with the clone reference
}
IEnumerator DestroyAfterDelay(GameObject cloneToDestroy)
{
yield return new WaitForSeconds(5); // Wait for specified delay
Destroy(cloneToDestroy); // Destroy the clone after the delay
}
}
ok so what I did is create a public GameObject pipeToDestroy; here and then I attached the GameObjects themselves onto their own DestroyerScript script. And this was supposed to force them to kill themselves not recreate themselves a billion times everywhere
if i have something thats becoming a System.. i'll put its own Script folder within it..
if its not or something more simple.. it'll just put its script within a Root Script folder
it's weird to have scripts/ but then have scripts elsewhere
No
i name my folders as such..
Scripts
- Utility
- AI
- UI
You are creating an object every frame. You got rid of your timer
No memes allowed here
ok
I tend to organize with a Root folder being the type of stuff
IEnumerator DestroyAfterDelay(GameObject cloneToDestroy)
{
yield return new WaitForSeconds(5); // Wait for specified delay
Destroy(cloneToDestroy, 5); // Destroy the clone after the delay
}
Vehicles - Vehicle Scripts, Vehicle Models, etc
I added it back in like this
ok so i realized why millions of objects were getting created
I instantiated on Update()
of my new "Destroyer" script
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class pipepositions : MonoBehaviour
{
public float upperExtreme = 3.19f;
public float lowerExtreme = -3.68f;
public GameObject PipePair;
private float spawnTimer = 0.0f;
private int spawnInterval = 2;
public void DestroyClone() // This function is not used in the current implementation
{
// You could implement logic to find and destroy a specific clone here if needed
}
void Start()
{
}
void Update()
{
Instantiate(PipePair, new Vector3(7.73f, -2.85f, 0), transform.rotation); // Store the instantiated object
Vector2 moveLeft = transform.position;
spawnTimer += Time.deltaTime;
Debug.Log(spawnTimer);
if (spawnTimer >= spawnInterval)
{
spawnTimer -= spawnInterval;
DestroyClone();
}
}
}
so now I added this back in again here on pipeposititions
and now the Destroyer.cs looks more like this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyerScript : MonoBehaviour
{
public GameObject pipeToDestroy;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void DestroyClone()
{
StartCoroutine(DestroyAfterDelay(pipeToDestroy)); // Start coroutine with the clone reference
}
IEnumerator DestroyAfterDelay(GameObject cloneToDestroy)
{
yield return new WaitForSeconds(5); // Wait for specified delay
Destroy(cloneToDestroy, 5); // Destroy the clone after the delay
}
}
You are just guessing with stuff. There is no timer limiting your instantiate call, and you are back to not caching instantiate too
Wait, this second one is all weird
yeah im not actually calling anything in on Update() yet
Wait, you are calling destroy from both scripts?
oops
In pipepositions? Because THAT is the issue
i didn't mean to do that
Destroy is not your issue, just to be clear. Instantiate is
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class pipepositions : MonoBehaviour
{
public float upperExtreme = 3.19f;
public float lowerExtreme = -3.68f;
public GameObject PipePair;
private float spawnTimer = 0.0f;
private int spawnInterval = 2;
void Update()
{
Instantiate(PipePair, new Vector3(7.73f, -2.85f, 0), transform.rotation); // Store the instantiated object
Vector2 moveLeft = transform.position;
spawnTimer += Time.deltaTime;
Debug.Log(spawnTimer);
if (spawnTimer >= spawnInterval)
{
spawnTimer -= spawnInterval;
}
}
}
Nope again
Every single frame this will instantiate something, make a variable called moveleft, add to a timer, check the timer, then subtract the timer if check is true
That timer has no affect on ANYTHING though
Oh, you also have the debug run every frame, sorry, skipped over that
Honestly, I would go back to this code
#💻┃code-beginner message
It was waaaaay closer
public Color myOwnColor = new Color(1, 0, 0, 1); can I not make custom colors like this? Cause if I try and assign somethings color myOwnColor, nothing happens, but if I assign it to something like Color.red, it turns red.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class pipepositions : MonoBehaviour
{
public float upperExtreme = 3.19f;
public float lowerExtreme = -3.68f;
public GameObject PipePair;
private float spawnTimer = 0.0f;
private int spawnInterval = 2;
void Update()
{
Vector2 moveLeft = transform.position;
spawnTimer += Time.deltaTime;
Debug.Log(spawnTimer);
if (spawnTimer >= spawnInterval)
{
Instantiate(PipePair, new Vector3(7.73f, -2.85f, 0), transform.rotation); // Store the instantiated object
spawnTimer -= spawnInterval;
}
}
}
fixed
Theeere we go
That does not store the instantiated object, so the comment is wrong haha. But functionally, now there is a timer
can you show where ur trying to assign this color?
now next goal is to get this bad boy fixed and make sure it works properly
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyerScript : MonoBehaviour
{
public GameObject pipeToDestroy;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
DestroyClone();
}
public void DestroyClone()
{
StartCoroutine(DestroyAfterDelay(pipeToDestroy)); // Start coroutine with the clone reference
}
IEnumerator DestroyAfterDelay(GameObject cloneToDestroy)
{
yield return new WaitForSeconds(5); // Wait for specified delay
Destroy(cloneToDestroy, 5); // Destroy the clone after the delay
}
}
I can, but does it matter? This color here and Color.red should have the exact same value, yet one works and one doesn't
by the way i just realized
Does it make sense to use Unity Version Control to avoid paying github lfs fees? My game is super simple but its 10 gigs folder
[Ll]ibrary/ is in my gitignore already
public class DestroyerScript : MonoBehaviour
{
public float timeToDestroy = 5.0f;
// Start is called before the first frame update
void Start()
{
Destroy(gameObject, timeToDestroy);
}
Alllll that is unnecessary. Just do this
and its still 10 gig?
lol isn't LFS free?
fixed it, I forgot to assign it in Start
🤦♂️
that PipeGenerator script is kind of a trojar horse meaning it looks perfectly fine on a first look but if you continue to play that script it will not permamently generate new pipes, it kinda as if PipeGenerator gets tired after 5-6 Pipes and stops. But at least Destroyer works properly
it's not a per file basis
What object is pipegenerator on?
ohh, there is also a soft limit of 100mb per file
yea
u have a team? it'd be worth it if u can split it up
ive only got 1 project that has issues on github.. and its because of all the audio. i chose to zip the audio files on my local drive and push the rest
that kinda saves me the trouble of finding an alternative
yeah so this got me wondering
does it make sense to have like a google drive or somesuch as developers
i use it
not to share / pull /push
but for my own resource
if u have just a hand ful of people using it.. i think google drive would be good for that
i decided just to pay, dont want to learn a whole separate thing and 50gbs means I can do git with any future game project
apparently it has backups and can revert to previous versions as well
one thing that is creating a big confusion i think iss that as code changes and scripts get new roles and need new descriptive names the class names dont get automatically changed as soon as you change the file name of the script so that is one thing creating confusion in my unity game project i think
if u click the class naem and right click and rename
Correct, they do not
it will also rename the file
Renaming the CLASS as spawn said, will rename the file if done right. Renaming the FILE will never rename the class
newer versions of unity don't require u to keep the class name and script name matching
but i do it anyway just for peace of mind
If Pipepositions is the script spawning the pipes, then yeah, you have a destroy script on it....
If it isn't the one spawning pipes, then I'm not sure why you showed those screenshots
wait if i rename the classname inside of the script does that also change the script name on unity?
it renames the script filename yes
cool to know
Misread, sorry
something i wish i would have learned about a year earlier than i did
does this call the moveLeft script?
I decided imma need to make a new Cloner script
cause PipeGenerator will be the one that will generate pipes inside of the upperExtreme and lowerExtreme
having a seperate Cloner script sounds more appropriate i think
no that creates a local Vector2 named moveLeft and assigns it to the objects transform position
do i need this Vector2 line?
ok so it doesn't do anything
nope, i dont see where ur using it anywhere else..
just assigns it.. and does nothing else
if u hover it it'll actually tell u that its Unused
i tried to create a 2d life bar but everything i try dont work
just start by debugging the values / getting the math working.. and then move on to setting a slider or a sprite's fillAmount to reflect it
alright thanks^^
Have you gone through the !learn course?
Or perhaps consider https://www.w3schools.com/cs/index.php
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Why? The bot call is right there
cuz
A new link wouldn't help that. But yeah, unfortunate
😦
Try googling the phrase "unity learn" and see if it comes up. Curious if it's a localization thing?
No idea though. Sorry
I opened it with unity hub, same results. Thats probably the case
you should do c# basics before unity. are you following a tutorial? i feel like ive seen this same sprite before. If so, go back and look at the code again.
Otherwise look at the error, you are trying to use a type and not an instance of an object
i used some youtuber's assets
for the pipes and the player bird
thats it
you really arent gonna get far just guessing at how stuff should be written. Do yourself a favor and do c# without unity first
i did the unity tutorial
followed the car tutorial and the plane project and it was good
but after that they have a whole tutorial about " okay now just go ahead and make your own stuff "
this is on the junior programmer course
but didnt do the c# basics course because I already saw their full tutorial on youtube about c# unity
and followed so many tutorial hell hour long playlists that now i think its time to create stuff
true
ok maybe there is some value in that c# without unity thing
I was surprised by the quality of SOME of their junior programmer videos ( but not all )
some where absolute dogshit
To compare this to something other than coding, right now you are experimenting with building a plane instead of putting lego bricks together
but the plane and car tutorials were so amazign they actually told me pretty much most than any tutorials on youtube
ok thats is true i agree
i tend to do that with other languages as well, its a bad habit
its less of what language you are coding in, but more about coding concepts. the above error is just that you are trying to compare a type instead of an instance.
I recommend following this interactive website https://www.w3schools.com/cs/index.php
i see it was also linked above to u
my project crushes when I encounter a creature, I'll provide the part of the code with teh problem, here: ```cs
do
{
StartCoroutine(WaitForAction());
ActionActive = false;
CreatureHealth = chosenAnItem(CreatureHealth);
textField.text = "He bit you!\n" +
$"You lost {rand} Health!\n" +
"Click 'Next' to continue";
StartCoroutine(DelayAction(60f));
} while (CreatureHealth > 0 && player.Health > 0);
and I really don't know how to resolve it
in other parts of the script, it does wait
wait...
then the while loop condition is always true, its likely not a crash, just that your game is frozen trying to infinitely run this code. Also those coroutines look questionable
Yeah!! how would you regularly resolve this issue?
Look further into why your while loop is always true. player.Health isnt directly changed here, unless some method changes it (the coroutines or chosenAnItem)
So that means CreatureHealth is always more than 0
Those coroutines make me wonder what they're doing, because its entirely possible you are starting many of them
yeah, wait I am snipping some code...
int chosenAnItem(int CreatureHealth)
{
if (chosenNumber == 1)
{
CreatureHealth -= rnd.Next(player.Weapon.DamageMin, player.Weapon.DamageMax);
}
else if (chosenNumber == 2)
{
Intermission();
}
else if (chosenNumber == 3)
{
textField.text = "Please choose an Item to use from above";
ItemHandler();
turnState = "UsingAnItem";
// Check if an item was used
if (UsedItem == "healingPotion")
{
player.Health += 20;
}
else if (UsedItem == "dynamite")
{
CreatureHealth = 0;
}
UsedItem = "";
}
else
{
StartCoroutine(DelayAction(1f));
}
return CreatureHealth;
}```
I wish there was just a wait(1) command...
I started learning unity yesturday
ok so what about the case where chosenNumber is 3, and used item is healingPotion?
or if chosenNumber is 2 i guess, look at what is returned. then look at the condition for the while loop
but it freezes... I can't see things retuned when unity won't react
you dont need to see it, you can think about it
Think about what happens if chosenNumber is anything but 1 or 3. Then think of the issue, the loop will go on forever if CreatureHealth > 0 & player.Health > 0
it doesn't work liek taht in the rest of the script, but I think I missed something gigantic...
wait
Also you can attach the VS debugger to play line by line, so your unity doesnt freeze entirely. Just need to put a breakpoint
it doesnt matter how it works elsewhere. just think about the cases i am telling you
this really is not complicated
public void Option3()
{
if (turnState == "InMarket")
{
if (player.Gold >= 200)
{
player.Weapon = new Sword("Diamond Sword", 100, 130);
player.Gold -= 200;
UpdateUI();
Intermission();
}
else
{
WarningText.text = "You do not have enough gold.";
StartCoroutine(DelayAction(1f));
}
}
else if (turnState == "InArmory")
{
if (player.Gold >= 80)
{
player.Weapon = new Sword("Diamond Sword", 100, 130);
player.Gold -= 80;
UpdateUI();
Intermission();
}
else
{
WarningText.text = "You do not have enough gold.";
StartCoroutine(DelayAction(1f));
}
}
else if (turnState == "FightingCreature") // Added condition for fighting creature
{
chosenNumber = 3; // Set chosenNumber to 3 to trigger item usage
Debug.Log("I have this SOOO much!!!!!!!!!! ayayayyay!");
}
else
{
WarningText.text = "You may not use this button right now.";
StartCoroutine(DelayAction(1f));
}
}
that you so much for the help so far, I really apreciate it
this function is triggered via a button
in game
I have no clue what the relation of these codes are, but wow thats a ton of string based stuff
do you want me to send the entire file? I feel like that might egsoust some people, and you
it seems kind of wrong to be honest...
(TEXT FILE)
!code for how to share code properly. But tbh im not truly interested in seeing it all. Ive pointed out already a possible issue, seeing more string based stuff isnt gonna change anything.
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
If you wont stop to think about that while loop condition, i cant really say much else
ok...
welp, Should I just stop working on this? I spent the past 18 hours working on this one problem nonstop...
I thought maby you could direct me to a better way to do it...
maby I was wrong, maby this was a bad project to begine with....
I made this project as a python project before hand, here is the file if anybody is interasted:
It's a project that I was very pashenate about...
it took me 26 hours...
I know I "need" to do what /!\code code tells me to do, but I feel like that's just a waste...
why do I end all my messages with ... 🤣 I just realized
i love reading 400 lines worth of strings 🤤
Can't read that without downloading a file, which I will not do
🤣🤣🤣🤣
you can
you can just click the button beside expand
'view whole file'
oh, that's a \thing with your settings
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I didn't know!, ok, amma start doing it
nice, thank you for providing me with that info, I was really confused
YESS!!!!! finally found the answer!!! yield return new WaitUntil(() => chosenNumber == 0);
Uhh could I get a bit of help with something?
I've looked at different errors im getting online but I'm not sure how similar they are to my code because it doesn't seem to work with their solutions.
I have the enemies all as prefabs with the 'Enemy' tag, and so I'm trying to have it to be when all the Enemies are destroyed, then the scene replays itself, but as of right now I keep getting errors related to 'Cannot implicitly convert type UnityEngine.GameObject to UnityEngine.GameObject[], which I understand its because it isnt being assigned as an array? But, when I try to change the code to something that doesn't show an error, I still don't think it is seeing the array as null? I'm not sure.
your enemy list is an array but you are using FindWithTag
you have to use FindGameObjectsWithTag
yeah, i noticed that in one of the solutions, i should've mentioned but that's what i was trying when it would have no errors, but wouldn't do anything
"wouldnt do anything" is very vague. i would recommend adding debugs to your code or providing more detail
right that's why i added uhh the print part, to see if that was the issue, and i believe it is
basically, when i destroy all of the enemies, the enemyList array should be null, but the print and function being invoked aren't running
i dont think thats how it works
is it not?
when there are no elements in an array, the array doesnt "become null"
you should iterate through a for loop to check if all elements are null
that should work
i was looking at code recommended in a tutorial, but i'll look at doing that and see how it goes
I'm not entirely sure how to go about this, I have this for the iteration, I'm not sure if it does work or not for sure
But if it does work, I'm not sure how to call a way for it to say like, an if statement for if it is true?
Wait sorry let me get this straight.
You want to have it so when all the enemies die, the scene resets after 2 seconds?
Yeah, that's the idea,
you can check if it works by adding a log inside the if statement you want it to reach. check the console during runtime to see if it appears . . .
The code above unfortunately isn't going to do it then. When you call FindGameObjectsWithTag, the array will contain all game objects with that tag in that moment. If you're destroying enemies when they die, then the entries in that array will progressively become null, but not the array itself.
it's an array, so it has a fixed size. it's length would never be zero (unless you initialize it that way) . . .
This function would work for checking that.
I found this function for the bool, so it isn't made specifically for my code, but if it's able to work even if it doesn't need the == 0 part then I can clean it up once I get it working
My issue is just that, in our class we haven't done like anything with bools, and I'm not sure how to go about making the if statement for if the bool is true, and if I did that I think it should be fine? Does the enemyList == null work in this case? I'm not sure if it's trying to see if the array is null or if it's contents are null, should I do enemyList.Length instead?
instead of array you should use List of enemies, each time enemy dies it removes itself from the list
enemyList == null won't work. FindGameObjectsWithTag will return an array regardless of if there's even gameobjects with that tag in the scene. It'll just be empty.
So, I guess I can try the list if that would work out easier? Or would I just need to use enemyList.Length or something like that?
use a list, check the Count each time enemies removes itself
Yeah I think I found something online that uses a list that would work.
I'll try that rq
as long as enemies have reference to that list in like a manager type script
Navaron is suggesting the correct solution. It just might be tough given what you know.
Ok but what if we bust out the degen shit and do GameObject.FindGameObjectsWithTag("Enemy").Length == 0 every frame?
🙃
How many GameObjects could they possibly have in the scene?
It's fiiiiine.
We're fiiiine.
not a lot of people know this, but unity actually does this on its own 😁 . Its just that... unity doesnt do it... and its me who added it to my script 😭
wanna support me ?? 😊😊 😇😇 💓
or just subscribe.. that would mean a lot too 😇😇😊😊💓💓🙏
device - vivo z1x /
disclaimer -
I do not own any of the music. copy right their rightfully owner.
" copyright disclaimer under section 107 of the copyright act 1976, allowance is made for "fair use'' for purposes such as Criticism, comme...
very very true
Alright, so, using a a list instead, I would need to change it away from FindGameObjectsWithTag right?
ideally yes
Ok wait hold up though. Why do you think a list is better?
Well, they had mentioned it, and I found something that had this code.
So, I thought that having a list might work? But right now I'm having an issue with List<GameObject> 'does not contain a definition for 'count''
no you can't just guess your way around it..
count doesnt exist...
Your !ide is not configured properly
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
• Other/None
the same way you cant use "count" for arrays
wdym you found a script?
at very least even stack overflow has more or less the idea
https://stackoverflow.com/questions/64759710/unity-listing-enemies-and-removing-them-from-said-list-not-working
when looking for other people having similar issues, this one person said they found a solution using a list instead, and it seemed pretty similar to what i was needing to do
just start from the basics tbh
You need to configure your IDE before continuing with any coding, as not having error highlighting and proper autocomplete is a waste of your time
thats what the class is for, but i need to improve off of this project i currently have
Trust me when I say code is not something you can smack together and expect to work, unless you know what you're doing.
Listen to vertx first, get your IDE set up so it can help you understand what's going wrong.
And then you can tackle the problem.
I can look at it, but I don't really understand this stuff, that's the issue uhh
it's literally just instructions you follow, that I linked
i've been smacking things together for the past few years and everything works fine for me. why do you think i love quaternions so much? 😅
Disgusting quaternion lover BEGONE.
yeah im looking at the VSCode one, but I dont see the IDE parts?
VSCode is the "ide"
the good stuff happens after Install part
Or maybe that was a joke attempt about how VSCode is not a real ide...😅
holy shit
"I'm looking at VSCode but I don't see ide anywhere"
Massive disrepect
so i just need the unity extension?
Incoming "But I have this Vim thing here"
That is one of the instructions, yes. There are a couple
okay i have that then and it showed i just had one of the counts in lowercase? and its saying no issues but i guess the code won't be working since it isn't made for it, since still no print or function invoked
do you see red underlines
I was about to say "then wtf is print" but then I checked
https://docs.unity3d.com/ScriptReference/MonoBehaviour-print.html
What?
are the enemies already in the list?
yeah its MB only and very old but valid
Why is it lowercase?
omage to java idk
very odd
same reason camel case properties 🤷♂️
See that ones not that bad (yet) because uppercase proprties are a relatively new thing in C#
or maybe infection from having a javascript like language at some point..
You've got 3 problems to solve.
- How does this script get all the enemies?
- How does it know when an enemy dies?
- How does it know when there are no more enemies?
do not speak of the dark times
right, im back now uhh,,
right, so it more than likely means that what they were trying to do isnt similar at all, I'm not sure how to actually get all of the enemies, I'm assuming I need to use something with the finding everything tagged as enemy, but i'm not sure how to put this into a thing to add to the list either, for knowing if an enemy dies I would need to check if it's null I assume, and if the list's count is 0 then that would mean there are no more enemies
i asked if enemies are already spawned or do you spawn them
already spawned
drag n drop them in the List
multi select
that should give you pretty much a list/count amount, from there just need to tell from enemy script to count/list script. " I died, remove me from list"
alright, cool i didnt know you could do that, so the for loop probably shouldnt be reversed like that i assume?
We could maybe make this simple for them and just have a script on the enemies that ticks up a static int on Awake and ticks it down on Destroy?
you dont need any loops
alright, how should i check it then?
enemies are already in the scene which should making caching the List script on awake a breeze
When the enemy dies run a function on the script with the List, count when you remove it from list
Sure but I feel like explaining to them how to get reference to this Manager script from the enemy is going to get rough.
they already were using FindWithTag
its not much more complex, change the tag to script with List of enemies counter
and call remove during OnDestroy on the enemy?
whatever Death method enemy has yeah they call Removal function
alright
its much simpler than polling everyframe with loops and whatever they were mashing
creating an array every frame is atrocious
I think their intension was to check if all the entries had gone null, to determine if all the enemies were dead.
yes very bad
the stuff for the enemy's death is in the laser's script, so basically when the laser collides with the gameobjects tagged as enemy, it destroys the enemy and the laser
either way they would need reference to the array to do removal at index, figuring out which index enemy is etc..
Alright. You're going to need a new script on the enemy.
enemy needs a script if you don't have one for sure
they have a movement script
alright
How we getting the manager on the enemy? FindObjectOfType?
as long as they understand why they are using this method 😅