#π»βcode-beginner
1 messages Β· Page 297 of 1
string, yeah thats the issue Im aware
hm.. is there a way I can make that script grab the value of the enemyType stat- actually wait Im not gonna need that
there we go!
thanks y'all, I rlly appriciate it ^^
this aint even giving me debug logs
which usually means the if statement is false
show where you have added the script to a gameobject
there should be a setting on the AudioSource/AudioClip component attached like "play on enable" - look for that and make sure it's disabled
I catch myself forgetting to do that too everytime I play with sounds π
its because redgrid i made it a gameobject
what do i do
what function does this work on
should post code
!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.
your error is that RedGrid is a type of game object and it does not contain a method of SwapTile
so you're mixing up your types here
ya need to post some code cause I am not playing a guessing game
so it might just call the function on the initial collision when the vase hits the table
a quick and probably slightly dumb solution would be to disable it for the first collision in the game, but I wonder if there is an easier solution for this
basically add a private firstCollision=true variable and add this statement to the onCollision function:
if(firstCollision){
firstCollision=false
return;
}
make sure it's before the sound-making functions though
feels dirty, but should do the job
it should be working
but when i put in the gameobjects for the public variables it says type mismatch
is there a way to "launch" player when clicking fast when using distance joint 2d?
private void Update() {
if (Input.GetKeyDown(KeyCode.Mouse0)) {
Vector2 screenPos = mainCamera.ScreenToWorldPoint(Input.mousePosition);
Vector2 gunTipPos = gunTip.position;
Vector2 direction = screenPos - gunTipPos;
RaycastHit2D hit = Physics2D.Raycast(gunTip.position, direction, grapplerDistance, grappable);
if (hit.collider) {
lr.SetPosition(0, gunTip.position);
lr.SetPosition(1, hit.point);
distanceJoint.connectedAnchor = hit.point;
// distanceJoint.distance = ((Vector2)gunTipPos - hit.point).magnitude * 0.9f;
distanceJoint.enabled = true;
lr.enabled = true;
}
else {
lr.enabled = false;
distanceJoint.enabled = false;
}
}
if (Input.GetKey(KeyCode.Mouse0)) {
lr.SetPosition(0, gunTip.position);
}
else {
lr.enabled = false;
}
if (Input.GetKeyUp(KeyCode.Mouse0)) {
lr.enabled = false;
distanceJoint.enabled = false;
}
}
``` rn it's completely stopping when i unhold my left mouse button
wait i think i know
probably because you reference the gameobject instead of the actual tilemap/whatever holds the swap function... you need to reference that component directly as the required type, or reference the gameobject, but first call a GetComponent<component with function>().function() in order to call it correctly
give it a shot, should be good to go if my assumptions are correct
it turns out it was a silly mistake i made
most bugs are because of silly mistakes you make π€·
i tried to put a gameobject in the scene to the public gameobject variable in the prefab
huh??
Its a bool
that can be whatever you want it to be, i just invented that to make it easy to understand what is it's purpose
oh shoot yep i forgot to put the type, should be private bool firstCollision=true
sorry!
i didnt,i was following a yt tutorail and i have put it in a folder called script
yup, basically:
private bool firstCollision=true;
void OnCollisionEnter(Collision col){
if(firstCollision){
firstCollision=false;
return;
}
myAudioSource.PlayOneShot(mySound, 1.0f);
}
anywhere within the class {} brackets
A script will not run if it is not attached to a game object
help please
how do i attach a script to a game object?
I guess you watch more of the tutorial
or !learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
yup, you'll get the hang of pretty quick once you know why certain functions are called and when, and then debugging becomes much easier, have fun!
nope, in the tutorial the code was working
listen, the code will not run if it is not attached to a game object. So...
if in the tutorial the code is running then at some point it was attached to a game object. So...
watch the tutorial again and this time pay attention
ok , after the code worked it was attached to a game object now i see, anyways thanks for the help
is there a way to "launch" player when clicking fast when using distance joint 2d?
private void Update() {
if (Input.GetKeyDown(KeyCode.Mouse0)) {
Vector2 screenPos = mainCamera.ScreenToWorldPoint(Input.mousePosition);
Vector2 gunTipPos = gunTip.position;
Vector2 direction = screenPos - gunTipPos;
RaycastHit2D hit = Physics2D.Raycast(gunTip.position, direction, grapplerDistance, grappable);
if (hit.collider) {
lr.SetPosition(0, gunTip.position);
lr.SetPosition(1, hit.point);
distanceJoint.connectedAnchor = hit.point;
// distanceJoint.distance = ((Vector2)gunTipPos - hit.point).magnitude * 0.9f;
distanceJoint.enabled = true;
lr.enabled = true;
}
else {
lr.enabled = false;
distanceJoint.enabled = false;
}
}
if (Input.GetKey(KeyCode.Mouse0)) {
lr.SetPosition(0, gunTip.position);
}
else {
lr.enabled = false;
}
if (Input.GetKeyUp(KeyCode.Mouse0)) {
lr.enabled = false;
distanceJoint.enabled = false;
}
}
``` rn it's completely stopping when i unhold my left mouse button
follow codemonkey tutorial and this is what he has
but when i try that i get this error
remove using Systems.Numerics from ur usings on top of the code
ahh got it thank you, no idea how that go there
VS autocomplete will add it
im trying to debug something, does anyone know of a way to like record the last value of a variable before the code reaches a breakpoint? is that possible?
like i know if its in memory visual studio does that, but when its not in memory it doesnt. i want to like record it before the GC erases it. idk if that makes sense
Uh, that's the default way?
You can just add a watch variable if it's outside your current scope if that's what you mean 
i have to google that, i suck at debugging lol
we all do, print() is the way brother!
print is good, but i have alot of printing to do, thats the thing
Print is easier for smaller problems yeah, but if you have a big problem, stepping through the code and checking if your assumptions match what the debugger says is easier imho.
the problem is, i have a bug that happens randomly. and its very rare too.
ive been at this for days now .-.
whats wrong with my code?
did u click and drag perseguir to the script in the unity editor?
spelling mistake postion
start by configuring your !IDE so you don't make silly spelling mistakes like that moving forward
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
is it necessary to use scriptable objects for a system that allows you to pickup/drop objects and putting them into an inventory etc
nvm fixed
ayyy π₯³
another error i found is that i typed "postion" instead of position in my code LOL
that sounds like your VS isn't configured
oh, I you shared a screenshot, it deffo isn't configured
Necessary? no, but SO's are good for storing data like you would have for items, enemies, weapons, etc
alright i just dont want to get into this inventory and then realise it wont work because of new items i need or whatever
SO's become cumbersome if you start having A LOT of items/ etc. If you're going to end up with hundreds, then another solution would be better.. if you're gonna have a few of each time, SO's are good
Hey guys i'm trying to understand how i should implement gravity change in my 3d game. I'd like the ball to stick to the left side by swapping gravity when the ball goes on the "black platform". I kinda achieved what i wanted but when gravity swaps the ball goes faster and it's kinda hard to control (you can also tell that by how fast the ball rotates)
What am i doing wrong? https://hatebin.com/cuvoqirjvz
you add force more than once per frame when gravity is swapped. also you really shouldn't be using AddForce in Update for continuous forces like that
physics should be performed in FixedUpdate to ensure it is consistent, because someone playing that with a higher framerate will end up applying more force than someone playing with a lower framerate
oh true
how do you suggest to edit the gravity part?
actually, i think fixedUpdate kinda fixed everything
so i have this code, and i have an error in firstpair/lastpair. below it says its 2,5,0 and above it says its 2,1,0
is my variable getting written and changed for some reason? am i reading this correctly?
above and below what?
above meaning when it gets assigned initially, and below when im trying to read it
oh my lord
π
so basically in this script the sky needs to follow the camera, how do i fix this?
you need to configure your visual studio so that it'll underline the error
you have typed something wrongly. it's not your logic that's the problem
i'm assuming you're using Visual Studio
how do i do that??
!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
VS code
then click Vs code
nah i aint understanding cause i did the same thing
i thought there was some weird stuff going on with passing by reference, but that wasnt it. structs are pass by value. im getting closer >.>
? Your ide doesnβt seem to be configured from looking at the Ss
probably because i got 3 C# extensions
!vscode
i think im going to package my project and see if anyone can fix my code, because i swear to god i feel like im poking at a bug in unity and i dont think i can solve this one
ill pass the torture onto you! π
when I pick up a slime, I made it so it faces the player camera. but for some reason its body rotates around if you move your view around? any ideas?
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float jumpForce = 10f;
public float forwardSpeed = 5f;
public float laneDistance = 3f;
public int currentLane = 1;
public float laneChangeSpeed = 5f;
private Rigidbody rb;
private bool isChangingLane = false;
private int targetLane;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
if (!isChangingLane && Input.GetButtonDown("Jump"))
{
Jump();
}
if (!isChangingLane && Input.GetKeyDown(KeyCode.LeftArrow))
{
SwitchLane(-1);
}
else if (!isChangingLane && Input.GetKeyDown(KeyCode.RightArrow))
{
SwitchLane(1);
}
}
void FixedUpdate()
{
if (isChangingLane)
{
float targetX = (targetLane - 1) * laneDistance;
float newX = Mathf.MoveTowards(transform.position.x, targetX, laneChangeSpeed * Time.fixedDeltaTime);
transform.position = new Vector3(newX, transform.position.y, transform.position.z);
if (Mathf.Approximately(newX, targetX))
{
isChangingLane = false;
currentLane = targetLane;
}
}
else
{
rb.MovePosition(rb.position + Vector3.forward * forwardSpeed * Time.fixedDeltaTime);
}
}
void Jump()
{
rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z);
}
void SwitchLane(int direction)
{
targetLane = currentLane + direction;
if (targetLane >= 0 && targetLane <= 2)
{
isChangingLane = true;
}
}
}
pastebin large code
Are you childing the slime to the character at all? I may be easier to tackle it that way
So what should I do?
yes
!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.
kinda hard to really grasp the pivot it's looking towards, but it seems like it gets too close to the pivots when you look downwards.
sorry I didnt know what all code to show. Specifically it is looking at the main camera object attached to the player. when an item is picked up it does become a child of the player object
Are you constantly using lookrotation in update? I think you can just set it once, then the localized rotation should suffice. I guess it depends how you're rotating the parent object
I did.
how can i do new lines in string in inspector?
you can use TextArea instead of string
wait
i need to research
I can't get help here :((
Anyways, bye.
thing is that the string is in a serialized dictionray
last i checked, you can't serialize dictionary. is this new?
its an addo
then i wouldnt know. you should share the full context of your problem
Can someone help me get better at c#? I'm a beginner I tried watching videos of variables and I don't understand it and gain nothing from watching those videos π
learn by example.. just start making
I don't know how to code so how can I start making?
can anyone explain how generic works, i thought i had learned it and it seemed that my theory about generics are wrong
so in this context i was trying to make a statemachine using generics and dictionaries, i tried it and it returned a null reference. After trying to find whats wrong with my code, i discovered that it was probably because of the dictionary not actually keeping the Enum value from the generics
public class StateMachine<State, StateEvent> where State : Enum where StateEvent : Enum
{
public BaseState current_state;
public Dictionary<State, BaseState> states;
public Dictionary<(StateEvent, BaseState), BaseState> transitions;
public Dictionary<BaseState, List<(bool, BaseState)>> conditions;
heres a portion of the code that involves generic as a parameter
and heres how i applied it on another script
[RequireComponent(typeof(NavMeshAgent))]
public class Enemy : MonoBehaviour
{
[SerializeField] private Transform Enemy_Target;
[SerializeField] private float update_time;
[SerializeField] private NavMeshAgent agent;
public enum state_event
{
allydies
}
public enum state
{
Chase,
Shoot,
Cover,
Dash
}
public StateMachine<state, state_event> SM = new StateMachine<state, state_event>();
private void Awake()
{
agent = GetComponent<NavMeshAgent>();
}
void Start()
{
SM.AddnewState(state.Chase, new Enemy_Chase(Enemy_Target, update_time, agent));
SM.setState(state.Chase);
SM.OnEnter();
}
lol, that's how you learn..
episode 24 he starts building something.. (everything up to that point is just learning material).. my favorite playlist..
this one starts str8 up making the game.. but id watch the other series first
then theres ur classic
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
i tested all of them, the code works fine
its just that current_state from the statemachine is still null but i did set it by doing AddState and setState
public void AddnewState(State state, BaseState baseState)
{
states.Add(state, baseState);
}
public void setState(State state)
{
current_state = states[state];
}
it was from that point that i knew that the dictionary is the problem here (i debugged the parameters)
thats comment
my b
raw string literals are a c#11 feature
you can do:
var string = @"
this is on a new line
";
or just use the \n character like you are doing there and just have it all on one line
lil help? π
provide the actual error
your dictionary is null. where do you initialize it
also for future reference: https://unity.huh.how/runtime-exceptions/nullreferenceexception
great
thanks, i got stuck for a day just because i did not initiliaze it
so i wasnt wrong
i love when programmer forgets 1 step and loses braincells unknowingly to what factor
It's called tunnel vision
you were so focused on the generics problem you forgot all the other basic stuff


yes
How come that ".enabled" is not something I can use with the generic Component class?
because Component doesn't have .enabled. Simple
This does though: https://docs.unity3d.com/ScriptReference/Behaviour.html
If you want help you're really going to have to start putting some effort into your questions.
it's telling you exactly what to do. Either ignore it, follow its advice, or change the name of your variable
use the new keyword :/
oh i got it , thanks so much
camera is an old Unity variable that exists in one of the inherited classes MonoBehaviour uses. It's deprecated and should not be used. You can use the new keyword to replace the variable. Alternatively name your field _camera to use a different name, considering your field is private anyway.
It's already been removed and deprecated. Hopefully they eventually fix the suggestions https://docs.unity3d.com/2022.1/Documentation/ScriptReference/Component-camera.html
I wonder if there will ever be a point where they remove all the bloat, including this
Hello. I have a question: I have an int variable that takes values from the slider, and also have a text that will convert this to text. So: Is it better to use int or Slider for text? Personally, I think it will be the same thing, or int will be somehow better. But I'd rather ask the professionals.
You should have one "source of truth" for your data, in general
in this case it sounds like the ints array is that source of truth
We're not professionals, we just think we're right
One says slider and the other says int?
But I don't get the question. Is slider a component?
Why would you have a second array when you have the slider already provide values?
The only thing I'd do is possible make a method that takes the value from the slider, so refactoring is easier
I need to take data from this slider for another thing.
Honestly, int is better, assuming you do need that array, as the value isn't converted in this case which is thus better for the performance. Additionally, it's shorter and more readable.
Yes, I tried and watched the guides, but there stupidly the float method does not change
Ok
It returns a float because sliders can accept decimals
But why do you have a separate int array? Because the slider returns a float?
If you just use it as a middleware because you want the response as an integer then just make a method that grabs the value from the slider
Then you can cast it like you did, but an even better way would be using this for example: https://learn.microsoft.com/en-us/dotnet/api/system.math.round?view=net-8.0
If we talk performance then a second array would cause for unnecessary allocation and thus be worse
That's why I have mentioned "assuming you do need that array"
Just grab the value using a method and round it. If you want the extra performance boost use aggressive inlining
I don't think the array is used apart from being some middleware for casting, but Molorochik can answer that better
Well, there is definitely a plenty of use-causes for an int array, which stores the same values as the sliders.
What I mean is, if their use-case is good enough, they should assign the text to the ints' i, otherwise to the sliders'.
They could've answered that better, hadn't they disappeared from the discussion though
If it werecs int[] ints = new int[sliders.Length]; for(...) ints[i] = ... text[0].text = ... ...you'd probably be well better off not caching the integer values just to avoid casting or accessing the value property of slider.
If it werecs [SerializedField] private Slider[] sliders; public int[] ints; public void UpdateCacheAndText() { for(...) ... ... }where you'd like others to have access to the values without having access to the sliders then it'd be fine or even necessary to cache the data.
Hello, my name's Azerul and I'm a newbie at Unity/C#. Currently, I am working on a project for a class in university, but I hit a wall;
I'm having trouble detecting collisions with capsule colliders on an Enemy AI using Physics.Raycast in Unity to spawn bullet decals on them. So far, I've checked the capsule collider settings, and the raycast does hit the collider, but my method( called DetectSurfaceAndTrigger) isn't being called.
Any suggestions or advice on how I can resolve this issue would be greatly appreciated! Thank you in advance for any assistance provided!
Oh, what's difference between a Component and a Behaviour though? Aren't those always connected
I will attach the code used in a bit
All Behaviours are Components.
Not all Components are Behaviours
You cannot disable a component
Neither can you start a coroutine on it
What is a Component that is not a Behaviour?
Rigidbody
Nothing shown in this code ever calls your function DetectSurfaceAndTrigger
Collider is surprisingly another one, though it does implement its own enabled property
I cannot use .enable on a RigidBody?
No
Weird
Tons of things.
You can check it out in the Inspector too
While there is a tick on e.g. a BoxCollider, which enabled and disables it, there is no one a Rigidbody
Don't they have the little toggle button on the inspector? Isn't that the .enable toggle?
Not on a Rigidbody
Oh, you are right, how weird, why is that?
Because Rigidbody is not a MonoBehaviour
And thus does not implement enabled
well it's not a Behaviour
Every Behavior can be enabled, MonoBehavior is thus a Behavior, Component
What if I wanted to get rid of a Rb through code?
Destroy it
I've inmported the probuilder package but my IDE isn't recognizing the UnityEngine.ProBuilder namespace:
or make it kinematic
Do you see this error in Unity too or only in VS?
Behavior is basically a Component, but with enabled and isActiveAndEnabled booleans
The collision is being weird, how does it keep damaging the player if the player is invincible? (logged the value is does become true when the player is invicne yet player still takes too much damage), also, when the player doesnt move.. they can stand and not take damage?
The package works fine in unity
vs just can't find the namespace fore some reason
Regenerate project files
It's UnityEditor instead of Engine right?
Thanks, never seen that happen before
ops, forgot to add the other code in the txt file
i hope im not asking for too much, but i think im ready to ask for help, i want to submit a bug to unity but i want help checking if my code is the problem first. i dont wanna waste some unity developers time because im not sure if my code is just bad
Also, can you share it using a paste site
!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.
Those of us on mobile cannot read it the way you shared it
can i post it to github? theres a couple of files you'd have to read :/
The recommendation is to use a site such as those listed above yes.
that pastemyst site listed in the bot message supports more than one file per paste
ok, i will post it to github and pastemyst
you don't have to do both, just choose one . . .
oh, then i choose github π
Hey, guys! I want to make on my game windowed and full screen mode. I have made the full screen mode but I am not sure of how to make the windowed mode. To note I don't want maximized windowed I just want windowed.
Can anyone help with that?
Yes, I know that! I have my documentation open on that
So what are you having issues with?
implementation of what
well, it's in the docs
If I am going to write that it will show that?
That one I mean?
show what?
In google
well, then you probably need to learn how to google things lol
otherwise you wont have a good time coding
In YT I just typed how to make full screen and windowed mode in unity
That's what I wrote
ok
I found nothing

Programming is like 10% solving logic puzzles and 90% Googling efficiently
searching on youtube != googling
that was related with windowed exclusively
but you had the docs open you said
Alright
so i'm confused how you didn't see it
show the code you have
huh
that is not code
I am searching in docs
and it's right there
And there I see not information for implementing the code
"Unity fullscreen windowed" in google
I linked you here to tth eappropriate place in the docs #π»βcode-beginner message
the docs IS the information
that's the whole point of it
That's why I linked you to it
do you even have your ide configured? @sage mirage
Yes!?
do you even know what are you doing? lol
I guess maybe you're lost because there's an assumption in the documentation that you can string together some basic C#
If you are having trouble with that part I recommend backing up and doing some basic C# tutorials
I know how to code XD
The whole problem was in searching the thing in how to implement it
Well again - I linked you to all you need here #π»βcode-beginner message
how did you learn how to code?
I am learning how to implement new functionalities that I probably didn't knew how to implement before.
and how do you learn how to do it
I am searching tutorials, trying to find useful information and trying to write it on my own at the end.
so what was different this time
For example new game mechanics
when after googling the very basic phrase how to make wnidowed mode in unity there are 3 pages of how to do it
Should I use a rigidbody and character controller on one player ?? Just asking, is it recommended ?
No, definitely not
Typically no, as they are competing movement approaches.
If you do - the RB needs to be Kinematic.
Ohh ok
Huh. Is there a use case for doing that? I had always thought it was just a hard no for both types
Actually I don't think so. I used to think you needed it if you wanted OnTriggerEnter but pretty sure that works directly with CC these days
Yeah, it does
OnCollisionEnter does not though
Only the trigger variety
ofc but that wouldn't work with kinematic RB anyway
True true
Same reasons for using a Kinematic RB in general - when you need an object to exert forces but not receive forces. The issue is that CharacterControllers really really do not like being moved by anything but their own functions. A Kinematic RB that moves from a CharacterController can be something other physics objects respond to, like knocking away small objects as you walk through them.
Ok, that makes sense. Thanks!
Btw, In the character controller.isGrounded, what is ground for this script ?
ok, im really ready now. πββοΈ please, whoever is willing to volunteer there time to check this out, i greatly appreciate it
https://github.com/celadaris/Potential-unity-Bug
That returns true if the previous call to .Move collided with something below it
i should also mention if you guys have questions about how this works, please ask. i may have not explained it well in the readme
You've dropped an entire unity project. If you want to know what a specific function is doing you could at least mention what file its in
i dont know what is causing the bug, but i think its in the DropTiles() function
which is where
TileSetter.cs
And what is the thing you're expecting to happen that is not happening
im expecting all of the tiles to be filled with a tile which has a sprite, but some tiles are left with a null sprite from before they are filled
Hello, I'm having an issue with IK for my animation. I'm trying to animate only the right arm of my character, I've created the mask and it works fine when I don't use IK target for my right hand. But when I use a rig for the right hand, I need to temporarily disable the Rig weight so the animation of the right arm work. I've created an animation event to handle that at the beginning of my animation, it does trigger but for some unknown reason, the weight of the rig is still 1 in the editorr inspector right after the break.
Here is my character rig and the logs
And here is my script
I'm checking the right hand weight to see if I need to cancel the IK. I do detect 1 and I then unpin the hand. I check the weight right after and it does debug 0 as expected
But in the editor, the rig weight is still 1
I've checked the character and rig name to make sure I'm using the correct objects and everything seems in order. But for some reason, the rig weight stays at 1 the whole time even after a break in the animation event.
How can that be possible?
The debug log show 0 but the editor shows 1
Is there some latency on the debug.break?
If I manually set the rig weight to 0 during the break and resume my animation, then it animates properly. But the script should have done that for me. Why is the rig weight stuck at 1 after the break ?
Hey I just want to verify something. I have:
public abstract class ChessPiece : MonoBehaviour
and
public class King : ChessPiece
so if I use getcomponent, can I get chess piece if my object has a king script?
yes
King is a ChessPiece
but you will get the reference as a ChessPiece reference.
ok cause I'm getting some broken references and want to make sure that the logic is right before I break something
this means you have a broken component attached to some object in the scene
it has nothing to do with GetComponent
none of the objects in my scenes or prefabs are showing as broken though
Ok to answer my own question, debug break does appear to only occur at the end of the current frame. Meaning there must be somewhere else in my code where I must change the weight back to 1... Just gotta find it I guess...
I searched a lot but still understand what is MVC and MVVM? What exactly they are ......
they are architectural patterns. and i doubt anyone wants to go through and explain how they work or how to design your systems to conform to those patterns
Why is unity adding using directives I don't need and then complaining?
Maybe I need to understand it with actual project? I just look the definition by searching in google that make my brain....
it's not unity adding it. it's you not paying attention to what you are selecting in your IDE when presented with multiple auto complete suggestions. or you are trying to use editor stuff in a build
why do you currently need to understand them?
So editor stuff should be regioned using # if unity editor, right?
yes, anything within the UnityEditor namespace (technically the assembly, but for this explanation just the namespace is fine) will not be included within a build
Hey guys, just starting Unity. Do anyone know how to make the type proposition appearing ? Like as the left screen
!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
you have already been answered. stop ignoring the answer you were provided because it will be the same answer every time you ask #π»βunity-talk message
Calling a bot is not really an answer lmao but fine
have you bothered following the instructions that the bot provides?
because that is the fucking answer
Do you guys also use cc.Move() on vector3 Y axis for jump ??
if you are using a charactercontroller, then you have to
Go touch some grass instead of being rude, you'll be more chill I think
Okay. I thought there might be something else in the character controller
mate, if you don't learn to read then you're gonna have a bad time using unity. follow the instructions to configure your IDE like you have already been told several times now
@raw spear bro dont talk back, hes just helping u
Now you're answering me, it's crazy that I have to remind you to be friendly to get a simple answer ty
"nOw YoU'Re AnSwERiNg Me"
my guy, i've pointed out the answer to you multiple times. if you cannot read the answer you're gonna have a bad time
If you're not going to actually take the help given to you multiple times, please leave. Stop trying to flame this into something it isn't.
Seems like I chose a bad time but im bad at maths rather than a multiple of .5 how could I make this a number that always ends in .5?
case 0: // Top edge
float randomXTop = Mathf.Round(Random.Range(-4.5f, 4.5f) * 2) / 2;
spawnPosition = new Vector2(randomXTop, 9.5f);
direction = Vector2.down;
break;
Now you're answering me
Dude it's the same they they already told you the last two times you posted this question. If this is an answer why didn't the other ones count
Seems it would just be easier to pick a random whole number and just add 0.5 to it after it's been chosen.
you could do &1 +0.5
basically round down and add 0.5
and there are no bad times to ask a question here, if the drama don't involve you you are safe
Hahah appreciate that, I think the best bet is to do what Osteel says and just add .5 to a whole number, do you know how I can make random.range generate a whole number?
I think theres a random.intrange or something let me check
pass integers instead of floats
oh cool
just note that Random.Range when used with ints is max exclusive
Welp i've only been learning to code for almost 2 years and now I find out I had the definitions for ints and floats backwards
the more you know
Thanks for your help guys
Wait, it isn't max exclusive with floats?
I mean I guess that makes sense to not exclude 10 if you include 9.99999
Oh, I guess that makes sense...
and typically we exclude the max for ints because our counters run one lower for indexing because of computer stuff
So I'm instantiating some placeholders for the move spots, and its creating them, but it seems like each instantiate creates 2 gameobjects, so how would I prevent that?
you're calling new GameObject() as the object to create a clone of. so you create a brand new empty gameobject, then you clone it
if you want an empty object just use new GameObject
then change its position to whatever you want on the next line
oh so don't use instantiate cool
instantiate creates clones
new makes a new GameObject
correct, you would use Instantiate to create a clone of something, such as a prefab. a completely empty, brand new, gameobject can be created using the GameObject constructor
ok that makes sense
sorry to ask again, but is there any chance anyone is checking my project on github? i think i may just file a bug. but i want to know if anyone is looking at it before i do.
Can you share the code having the issue with a paste site.
you kinda dumped the whole project
just sharing the specific script that has an issue and explaining the specific issue would be better
the problem is i dont know if something outside of the scipt is causing the issue
You also didn't really explain the bug
you just said "there's a bug that happens"
what does that mean
its in the readme on the github
its too long to explain how the project works here, i didnt wanna flood the chat
Yeah I read it
the function name is GetSprites(), this scans every tile to check if they have sprites if we have an empty space because it was not properly filled in the DropTile() then that displays the bug.
This doesn't say anything about the bug
it just says "that displays the bug"
thank you, im gonna re-read it
I'm using CreateShapeFromPolygon, and I've added the mesh and created the shape (presumably), but the shape isn't rendering
for (int i = 0; i < 6; i++)
{
float angle = Mathf.PI / i;
uIPoints.Add(new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)));
}
GameObject go = new GameObject();
mesh = go.AddComponent<ProBuilderMesh>();
mesh.CreateShapeFromPolygon(uIPoints, 0.2f, false);
there should be at least a wireframe of a little hexagonal prism, right?
yeah the meshes don't appear
is there any way to use Mathf.Pow with a double as an arguent?
use Math.pow
Mathf is Math(float)
i think it accepts float only, but if u do need then u can convert from double to float
System.Math has a double function for pow
to big for that
mm but i think doing so results in a loss of precision, since float has a lower precision compare to a double
yw
:D
Hi all,
I've been thinking about this for a while and can't figure out the best way to do what I want to do.
I want to create a 'swarm missile' kind of thing (See pic for reference)
I'd like the missiles to launch one at a time in quick succession and then each one head towards a seperate target. The targetting I'm pretty sure I can do no problem, but I'm not sure how to do the flight path of each missile (I'd like for each of them to come out from the players body and then travel to their target in a smooth arc kinda thing (if that makes sense)
Anyone have any ideas?
i made a couple more edits, my wording was still bad lol, im sorry
Just explain it here in 10 words.
If you can't explain it in a few words, then you need to refine what you are thinking about
I imagine starting with either random or prespecified unit vectors, maybe like RandomInCircle, to determine the initial path, and then have that initial path lerp into a path that is going towards the object.
probably the point where you find the initial vector would be a good time to lock on a target too.
@summer stump i put my readme in chatGPT and asked it to summarize in 10 words:
Automated game tile replacement glitch; incomplete tile filling after drops.
Bad choice
it explained it well tho
No it didn't hahaha
im sorry if i sound snarky, im not trying to :/
What does drops mean? What does tile filling mean?
ok let me retry
The first 5 words are completely unneeded
Do NOT use gpt
ok
Yeah, that's the thought I had, I was thinking of putting the targetting/travel code on the actual missiles (travelling transform.forward), As they spawn, they grab their target, keep track of the targets position and lerp from their 'launch' rotation to pointing at the targets location. Just wasn't sure if there was a better way π
I mean the traveling is only necessary as long as the missiles exist, so it makes sense to keep all of that info with the missiles
Yeah, and they'll be very short lived (it's quite fast paced).
@summer stump so i have a 2d game. it uses a tilemap. the tilemap is filled with tiles. i want to delete a random tile in the tilemap and i want to lower the tiles on top to replace the deleted tile. then i want to fill the space on top with a random tile. The problem is not all tiles are getting filled. so im left with holes where some of the deleted tiles are.
you could probably do some math with bezier curves or something if you want a more flamboyant path but that should be the gist of it
Honestly, I spent all day dicking about with Unity Splines and I never want to see one again. lol.
Yesterday I mean. lol.
Ok. So first (sorry) this is not a code issue then. Go to #πΌοΈβ2d-tools and paste that exact statement in. Not much more is needed. If they ask for more, give it then.
But yeah, I think that explains it well
i am controlling the tilemap and its contents though code, not with the editor tool. would #πΌοΈβ2d-tools still take care of it?
Yeah. They can help with code when it is specific to 2d tools like the tilemap
ok ty!!
Sounds like you want the tilemap to collapse down kinda like Tetris does.
yes!
could have the projectile launch vertically (apply velocity to the local y axis) and then call transform.LookAt(target transform)
is it possible to hide a component like you can in the inspector, but in code?
That was my very first thought, but LookAt is an instant turn. But I think I have a solid idea now, I think RotateTowards over time is probably the way I'll go.
I know I can SetActive to false for a gameObject but i just need to hide a component in that gameobject
can't you specify a timeframe with LookAt? Guess not
what do you mean Hide ? @buoyant meteor
component.enabled = true/false
you can't hide a component at all ?π€
Yeah you can't hide them but you can turn them off.
ya turn them off
this isn't hiding, it's toggling it on/off .. and only for the Unity magic methods
Yeah, I realised I'd read the question wrong as soon as I posted, so I posted a correction. π
If your class doesn't have a Unity method , then the enable is pointless
disabling only disables these methods
so toggling the canvas seems better to me.
If you have public or serialized variables etc. that you want to hide, you can use [HideInInspector] (I think that's the line) to hide them.
anyone know how to add a rigidbody's force relative to another object's rotation? currently doing this but it really doesn't work propertly and I can't figure it out cs m.rigid.AddForce(Quaternion.FromToRotation(m.orientation.forward, relativeForce.normalized) * relativeForce, ForceMode.Impulse);
Guys, I want to add a four way intersection to my driving game. However, I want to also add traffic to my game. So far, I've just bee using objects as waypoints for the car to follow. However, when it comes to intersections, there are various paths that the car can take.
My initial approach was setting up 3 lists for each direction of approach for a total of 12 lists. But then it seems like a lot of waypoints. I feel like this has a simpler solution. Any suggestions would be appreciated!
also for anyone wondering, toggling the canvas fixes the issue of having an item getting stuck on screen when disabling(closing inventory) an object while holding an item in a random location.
So what part here would be a Unity bug?
Seems like you just have a bug in your code.
Also does anybody know how to not allow an item to center onto a item count gameobject.
in each of my inventory slots I have a gameobject called itemCount to store count value
but if i drag an item ontop of an ItemCount, it will center onto it.
i cant say for sure if it is a bug in my code because the problem happens at a random location, and after a random duration. at least to me thats what it seems.
it's definitely a bug in your code.
why is a null sprite considered a bug here?
because its supposed to get replaced with a actual sprite?
or should I simply add the itemcount to my item object?
and what part of your code does that?
Are you asking hjow to call SetParent without modifying the position?
Check the docs for SetParent: https://docs.unity3d.com/ScriptReference/Transform.SetParent.html
no
in the TileSetter.cs file:
Vector3Int tilePos = new Vector3Int(lastPair.x, lastPair.y, 0);
tilePos = new Vector3Int(tilePos.x, tilePos.y + 1 + i, 0);
//get the tile above the stack
TileBase upperTile = tilemap.GetTile(tilePos);
tilePos = new Vector3Int(firstPair.x, firstPair.y, 0);
tilePos = new Vector3Int(tilePos.x, tilePos.y + i, 0);
//drop the tile above the stack
tilemap.SetTile(tilePos, upperTile);
how does this set a sprite
it is supposed to replace the tile with the null sprite, with one that has a sprite
i have checked and added break points to make sure that it has a sprite, and the breakpoints never get triggered
to me it looks like your just setting a tiles position but not sprite
tilemap.SetTile() takes a vector3Int which is the position of the tilemap and takes a TileBase and places it in that location
I guess maybe one of your tiles doesn't have one
But I presume you're using a special GameObject tile or something here
because normally with tilemaps, GameObjects aren't really involved in each tile
it is a ruletile
and i would agree with you if breakpoints got triggered
which breakpoint
hold on
I gotta respect @wintry quarry for helping alot of people out today, including me.
i might be onto something
nvm
darn lmao
ok back to the question
@wintry quarry the breakpoint isnt in the script but if i make one and run it then it doesnt get triggered, like this
but how does that matter to the other thing?
your other code is checking ALL tiles right?
this code is only checking some
correct, i can everywhere where i am filling the tiles, and to my understanding i am filling the tiles everywhere where i could. but if there is a special condition where im not filling them then it isnt a unity bug, but just my bad code
yes
Unity is not going to do anything with this as a bug report right now
you'd need to show an isolated scenario in which Unity itself is clearly doing something wrong
is there any way i can make this sprite fully white?
the problem is, to my knowlege i dont have a special condition
right now we have a very nebulous situation where it's most likely a problem with your code
in photoshop
but i cant prove that it is. and i need help
yeah but i dont wanna do every single one manually
i need to do it automatically
like a shader?
what are you trying to do?
why do you want it white
sure you could use a shader
because i want some slots to indicate what items can be placed inside
so have like a white transparent overlay
onto the slot
Unless you have really compelling evidence, it's safe to assume it's not a unity bug.
what i know is that a null sprite will always appear in the while loop. if i comment out the while loop then my code is perfect. and why is that? could there be some kind of problem where calling tilemap functions too many times in a while loop causes problems? i dont think i can debug that.
no
it doesn't matter how many times you call the functions
which while loop are you talking about?
its too big, i wanna do pastebin or something
crafting system
so u see those items in those cells?
they arent actual items
they just show u what items are supposed to go in what cells
so i just need them white and a bit transparent
use a shader, sure
@wintry quarry im gonna try to reproduce the bug with less moving parts. It might help.
Hello, i have a behaviour script where at one point it should delete itself (as in the game object the script is attached to). If i say this, is that referring to the script or the game object because it's not deleting properly
show script
Destroy(gameObject);
Destroy(this.gameObject);
Destroy(this); will destroy the component, not the gameObject
Thanks, this worked perfectly
How can I check if a button is pressed or held? Since I think just using get button down would trigger if it's pressed briefly and I want to assign different functions to each.
Depends on which input you use.
Assuming old, GetButtonDown vs GetButton
For new InputAction.IsPressed()
Highly recommend moving on to the new input system
is there a new input system for keys too?
I've got a lot of stuff already made with the old system so it seems like too much of a pain to switch for this project
like something to use instead of onKeyPress
getbutton would return even if it's just clicked though right?
How do I get script created meshes to render?
Maybe have a bool that is set to true when button pressed, then false when released
Then just check the bool
You need a meshfilter and a meshRenderer with all the 'stuff' applied.
OK cool thanks
Yes, you have to check the time yourself
Make a timer or coroutine
Ok. Too bad.
Meshfilter needs the mesh applied, and the meshRenderer needs the material applied (I'm not sure about all the other stuff needing parameter set tbh, not something I usually do)
Yeah, thanks, I'll look into the docs
Not doing too much with it
Okay cool. π
That smile is so sad
lol.
They really need to match the energy of
:)
!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.
you guys know that you can turn off the auto emoji stuff right? :)
Tell me your secrets
lol.
You can also do it with an escape character :)
Sooo, having a brain freeze moment (surprise surprise).
What's the syntax to get an object to remove itself from a list at it's specific index?
Do you want it to remove itself from the list, or remove the item at a specific index? Those are two different things
1 sec.
Would this be the correct way to check if both colliding with a specific trigger and also the "e" key is down?
public void OnTriggerStay2D(Collider2D collision)
{
if (collision.gameObject.tag == "tag")
{
if (Input.GetKeyDown("e"))
{
//random code here (not really imortant)
}
}
}
i want this specifically only for the frame for the e key to be pressed
collision.gameObject.CompareTag("tag") && Input.GetKeyDown(KeyCode.E)
Doesn't getkeydown detect continuously?
Okay, vid for reference. public list on bottom right.
at the moment I'm using
spawnManager.enemyList.RemoveAt(spawnManager.enemyList.Count - 1);
Which is fine, I guess, but I can see the 'Missing Transform' entries in the list being a problem at a future point, so I'd obviously like to remove the objects from the list 'directly' (not sure if that makes sense)
no
The more you know
Hey when I run the code in editor, it 50% pauses the game, 50% doesn't. The menuState is always entered, just the isPaused bool is ignored and the subscribed event does not execute.
https://gdl.space/uyagiwucej.cpp
tldr: OnGamePaused?.Invoke(value); does not execute
read the docs π
"Missing Transform" usually means an object that was in the list was destroyed.
If you want to have this object remove itself from the list, do .Remove(theObjectToRemove). Right now you're removing the last element of the list no matter what is destroyed
Yeah I know. When the enemies pass the camera they get removed, so that's why I want to remove themselves from the list.
Aaah okay, thanks, just couldn't remember the syntax π
Would this be the correct way to check if both colliding with a specific trigger and also the "e" key is down?
public void OnTriggerStay2D(Collider2D collision)
{
if (collision.gameObject.tag == "tag")
{
if (Input.GetKeyDown("e"))
{
//random code here (not really imortant)
}
}
}
no, the chances of the key being pressed on the exact frame the collision occurs are virtually nil
it's TriggerSTAY - should be fine?
and it seemed completely random
If your game is running at 60 FPS, that'd mean you need to press the "e" on 1 out of 60 frame
i dont want it to be held down, i want it to be where if its pressed while the red "ball" is touching the grey trigger
the thing on the right side is a different prefab
The issue is that OnTriggerStay occurs in FixedUpdate, but GetKeyDown changes in Update. Meaning depending on your framerate, you might end up doubling up on Updates between FixedUpdate calls and that button press gets "Skipped"
yeah, I looked, I thought it was happening a lot more often than it is
What you want to do is set a bool to true when you enter the trigger, and false when you exit. In update, check if that bool is true, and if you're pressing the button
It might be better to set a bool onTriggerEnter = true / false
okay, thanks much!
bump
Which code?
why cant I create a new clone in the parrelSync?
did you read what it says?
apparently you're in the clone and you cannot create additional clones from clone, open original project
Did you truncate it yourself for GDL?
What calls MenuState()?
Yes.
In the inherited class, FSM. It's inside Start() and called _gameStateFSM.Start(_menuState)
That start is unrelated it seems. The menu state logs fine, it's the bool that has a 50/50 success rate
And yea, the bool then has invoke, then invoke relies on events. So that's when I am lost
I haven't used an FSM before..
When you call _gameStateFSM.TransitionTo(_gameplayState); is the case FSM.Step.Exit: in MenuState being actioned?
they've tried to improve unity editor execution to run similar to a built exe, but some things listen for different events, like EditorApplication.isPaused = true;
Yes, Exit seems to be fine.
If you're wondering if Exit is immediately called, it isn't.
It goes:
- Press play
- MenuState enters (calls Enter)
- 50% chance the property IsPaused invokes OnGamePaused event
So the FSM doesn't seem to be an issue from my testing
if you comment out your (value == _isPaused) check, does it make it 100%?
true
Nice, didnt know that existed. for this code though I am using custom events
Yea, nice. That fixes it. No idea why that is broken... it shouldn't be, right?!
I guess the backing field is getting updated at the wrong time
Not mentioning anyone but someone here explicitly told me to put that there and it worked when I had it before... So glad I found it but that's really odd
not always before it needs to
If i have a script attached to a prefab, can I drag a pre made game object into that script still? its saying Type Mismatch and I don't know why
Just get rid of the backing field, why's it there?
_
backing field: private static bool _isPaused = false;
property:
ublic static bool IsPaused
{
get => _isPaused;
set
{
if (value == _isPaused) return; // Do nothing if value doesn't need changing
_isPaused = value;
OnGamePaused?.Invoke(value);
}
}```
To my understanding I can't do without in it C#. I'm using the field to record the data if the game is paused or not for the Getter
Change the property to
public static bool IsPaused
{
get => _isPaused;
private set
{
if (value == IsPaused) return; // try this, if it doesn't work, remove
IsPaused = value;
OnGamePaused?.Invoke(value);
}
}```
it is not needed
But you still use it twice in this example? Sorry if am misunderstanding
im trying to reference a script from another object, but i keep getting an error. im doing this so that i can change a variable on the gamemanager that keeps track of credits used by enemy spawners. does anybody know what might be wrong?
first configure your IDE
also using Find is horrid
it is?
yes but your colors don't look right
Should look like this and say "Unity Message" next to references
nah not for vscode
Oh sorry, thought it VS. I don't think they call vscode an IDE
it becomes an IDE with extensions sure
so what else should i do?
do you have the Unity extension installed in vscode
yes
try regen project files from the screen you just showed me (close vscode first)
then open script from Unity again. Observe the Output tab for any errors
Did you find a way? I'll just go get something and AFK. If you do please lmk, I'd love to delete the backing field if I can
And thanks for the help i really appericate
no, sorry, you're right.. it's needed in this case. I left it in before because I missed it.
If you do public Bool MyBool { get; private set; } no backing field is needed, I think if you add more to the set then you need the backing field
how do i regen project files?
bump
click the button that says Regenerate project files?
You can only add other prefabs into a prefab
you cannot add scene objects into a prefab
unless the prefab is like in the hierarchy of said scene
Type mismatch means something was assigned before, but now the field type has been changed and is a different type.
A prefab can't have a reference to a scene object
this is the earlier error
it still says theres an error
finish configure ur IDE first
same one
again you cannot use constructors on MonoB scripts
i did???
its not tho
so what do i do??
ohh okay this is very helpful thanks!
ive been told to use a singleton so im gonna look that up and do that instead
Oh cool good to know, so private keyword makes the backing field automatic? Thanks for help
You cannot use Find outside of a method
You also probably shouldn't use Find at all
just note a configured IDE is requirement to get help here..
if you make further syntax error we cannot help
its configured to the best of my ability. im not sure what you mean by an output tab
mate i was guiding you through it and u stopped responding
ima go back to watching people get bit by snakes, good luck
:(
That won't help you with what nav is talking about. You are required to have a configured ide to receive help here
Ah, lag
No, the private accessor means only this class can set it. This doesnβt require a backing field
public Bool MyBoop { get; set; }
would you at least know where i could find the output tab?
Vs or vscode?
vscode
Should be at the very bottom. If not, you can open it from the "view" menu at the top I think
aha! thank you!
so i have a gacha code where you can pull things and it will instantiate an item in a list, which is from this first code, but i want to place it in my inventory, but im not sure how i should do that:
Well that all depends on your inventory works
i was following a tutorial for picking objects with collisions which will enter it into the inventory, but theres not anything from like putting it into the inventory from the gacha
idk how to explain
!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.
kk
More woes with loops inside Coroutines. lol.
So, you can see on the bottom right that the enemyList gets filled up correctly.
But, if you look at the debug, only 5 missiles spawn in so the loop isn't running fully and I'm not sure why.
IEnumerator PlayerShootMissiles()
{
float missileCount = 0;
// TODO : Swarm Missile Firing
isFiring = true;
missileTimeToFire = Time.time + 1 / missileRateOfFire;
for (int i = 0; i < spawnManager.enemyList.Count; i++)
{
if (Time.time >= missileTimeToSpawn)
{
//spawn missile
GameObject newMissile = Instantiate(playerSwarmMissile, missileFiringPoint.transform.position, missileFiringPoint.transform.rotation);
PlayerSmartMissiles playerSmartMissile = newMissile.GetComponent<PlayerSmartMissiles>();
playerSmartMissile.target = spawnManager.enemyList[i];
missileCount++;
Destroy(newMissile, 2f);
missileTimeToSpawn = Time.time + 1 / missileSpawnRate;
}
yield return null;
}
Debug.Log("Missile Count = " + missileCount);
isFiring = false;
}
this is probably a better way to do this actually
dokomni i think i know your problem?
are you wanting to access a variable that is from a different script?
yes, mainly a credits system between spawners so that they stop spawning enemies once they run out
im having a hard time explaining this lol
im probably gonna make an example sorry for the wait
Hello, guys! I am trying to make the parallax effect on my 2D side scrolling game and I actually made it but I am not sure of how to stop it when my game goes over or pause?
{
if (RoundManager.Instance.currentState != GameState.GameOver || RoundManager.Instance.currentState != GameState.Pause)
{
distance = distance + (Time.deltaTime * scrollSpeed) / 10f;
mat.SetTextureOffset("_MainTex", new Vector2(distance, 0));
}
}```
no its alright
Here is my code
Maybe look at Singletons? You can keep a 'global' count of 'credits' really easily
Set scrollspeed to 0 ?
can someone help me make a shader to make these image sprites white?
missileCount is only incremented if Time.time >= missileTimeToSpawn. Seems like this occurs 5 times before you run out of things in enemyList
Thanks!
class Bob {
public bool cool = true;
}
//your other class that you want to transport it to
class OtherClass {
//drag GameObject that has your script with variable attached to it here
public GameObject objectWithScript;
public Bob bobObject = objectWithScript.GetComponent<Bob>();
//You can then do:
if (bobObject.cool)
{
Debug.log("He's so cool");
}
}
they dont need to be in the same script i just did that for easy sending
yeah, that's the idea. Basically, if I press Space, the player launches the same amount of missiles that enemies exist in the list, Time.time >= missileTimeToSpawn is a small delay between each missile fire.
i see
- You can't use GetComponent outside of a method
- What's the point of having a field of type
GameObjectthat exists solely to get a component from? Just makeobjectWithScriptof typeBob
Is it possible that PlayerShootMissiles() is being called when there are only 5 enemies in the enemy list?
It could be better to pass in the amount to spawn
private IEnumerator PlayerShootMissles(int misslesToFire)
{
for (int i = 0; i < misslesToFire; i++) { }
}```
So, you check one enemy per frame. If Time.time >= missileTimeToSpawn, then you run the inner code that increments missileCount. If that condition isn't true, you wait one frame and then move on to the next enemy.
- sorry, im new to unity and didnt know this wasn't allowed (I initialized it in Start, and if you want to use it like this you should too)
- Sorry, I'm confused what this is saying
just trying to help π
its an automatic thing in discord, you can change that in settings somewhere
The first variable of type GameObject is completely pointless. Just make a public variable of type Bob and drag it in
I've got a check in place to only be able to fire when the amount of enemies in the list matches the number of 'cells' in my side/side moving grid.
Wait, so you can just put the script into the other?
If I sort a list of floats can I make another list be sorted in the same way? For example if I have a list of (gameobject3, gameobject1, gameobject2) and another list of (3,1,2), can I apply the order from sorting the list of numbers in ascending order to the list of gameobjects?
If you have a public or serialized variable of a component type, you can drag in an object that has that component
I have some changes to make lol. stupid coding mistakes.
Press Space, check if enemyList.count == formation.cellCount. If yes, then the for loop runs enemyList.count (18 for testing) times, each time spawning a missile (with a tiny delay between for loop iterations so they don't come out all at once.) I think that makes sense. lol.
I'm telling you exactly what your code is currently doing.
You loop through your list of enemies.
If Time.time >= missileTimeToSpawn, you run the inner routine.
Regardless of whether the inner code runs, you wait one frame, then move on to the next enemy.
Sorry, my bad, misunderstood.
NullReferenceException: Object reference not set to an instance of an object
GameManager.PlsEndTheGame (System.Boolean value) (at <0d5d04fcd9354ff5925088743d7c08fa>:0)
Timer.Leave () (at <0d5d04fcd9354ff5925088743d7c08fa>:0)
Timer+<TimeIt>d__19.MoveNext () (at <0d5d04fcd9354ff5925088743d7c08fa>:0)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <00d5b91f2c49467b95ced8aa41db73be>:0)
What exactly does this mean? Am new to events and wonder why this wont work. Bcs the game manager script is on an object
Its even a singleton
(it works in the editor)
You're trying to reference something that the script can't find at runtime.
I'm guessing this is from a build, since you don't have proper line numbers. Does the error occur in the editor? If not, try building a development build, it's a checkbox in the build settings. It'll include the source so you'll get a proper line number
So, is that what you want to be happening?
Ah, no. I see my mistake. what I want is that each time the for loop iterates, find enemy, fire missile, give missile found enemy transform.
It's not necessarily GameManager that is null, what's PlsEndTheGame, that could be null.. or something else on that line
So, you want to loop over the enemies, fire at the current one in the loop, then wait some amount of time before continuing the next iteration, correct?
Yes.
Fixed it. lol. Thank you. π
I have subscribed to the PlsEndTheGame event Action<bool> and the error leads me to the first line (Environment.SetActive(false);)
private void PlsEndTheGame(bool value)
{
Environment.SetActive(false);
...
Can it not be the same name?
cellSprite.material.shader = Shader.Find("Sprites/Default");```
this changes every cells material shader
should each cell have its own material?
or how do i go about this
anyone?
fixed! all i needed to do was this.
That could certainly be your error if Environment is null, but running it in the editor or a dev build to get the actual line number would be best
Ah, I just missed that, I see now. So it is that line, meaning Environment is null
Weird bcs its assigned in the inspector
There exists at least one instance of this script for which Environment is null at the time that function runs
So I may have 2 gamemanagers?
Surely that else if wants the player.isInvicible == true where as atm it's == false
Possible. Or you might be un-setting the variable, or the object it was set to might be getting destroyed
But the error is stating that at the time that code runs, Environment is null on that object
i changed it to just this
how to get a child gameObject from it's name in a parent's script?
oml are you kidding me environment is nulled at some point uhhhhhgg
public Material material;
private void Start()
{
material = new Material(cellSprite.material);
cellSprite.material = material;
}```
why is the material not getting assigned?
@hexed terrace what i meant is that the player still takes more than one damage, even when becoming invincible
which i dont see why that happens
also, if u were standing still when the ground becomes lava u dont take dmg if u keep still π«
those are the current problems and my question is why and how to fix
I understood what your issue was
What calls GroundColStay() ?
From this code, health shouldn't be reduced if the player is invincible.. so , there's probably more going on somewhere else that you haven't shown
why cant i assign the material like this?
Show the full !code for InventoryCell
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
so i found the problem
there isnt a material
how can i create an instance of the default one?
the Default UI Material
Create -> Material
i'll just make my own material
Yes that's what I just said to do
seems pointless, how come you do that?
https://gdl.space/awokuqeveh.cpp here is full script
wait it still doesnt work
idk i just organize all player collision liek this
i feel like it becoems easier to break it down into parts
and line 44
You left off a very important factor
The fact that you're trying to use it in the Refresh method before you set it
So next time, don't omit things you think aren't relevent because those often end up being what the problem is
that makes sense now
sooo... what my thoguht process is that player takes 1 dmg, becoems invicnible (happens whenever player takes dmg) then cuz the player is invincible it wont take damage
however
player still takes damage
Hey there. Is there a way to set the pivot point of an object without having the make it a child of another object. In my case it also needs to happen during runtime
pls i legit cant think of why π’
how to make it so that when I pick up an object it does not move, but is fixed on a point
log out if the floor is lava
your if statement has two bools, you know one is correct (player is invincible), but you don't know the other is correct - log it out
you could rotate around a pivot, or move using a vector as a pivot, though, that would be more work/code . . .
but the pivot is set from the 3d modeling program . . .
Yeah I haven't found any good solutions online sadly
those are the only solutions . . .
the thing is both have to be true... but player.isInvicible shouldnt, like its:
Yes I figured there would we a better way but aparently not...
Weird smt simple like that cant be done another way
i know floor is lava is true cuz also the floor changes sprite
Instead of trying to guess, check. Log both bools before the condition and see if they are what you expect
If a raycast hits nothing, is the corresponding RaycastHit.Distance supposed to be 0? (when maxDistance parameter of raycast is non-zero)
just log it out fgs, stop wasting time π
Not sure I understand the question, but that is a very incorrect use of lerp there
The third param is not a speed
i... okay one sec..
I need to grab an object
how might i change an int value called "credits" in a script called "credit" which is referenced this way? (gets it from the "credit" script on the CreditKnower gameobject)
you cannot access a private field from a script . . .
create a method on the script that changes the internal credits value . . .
on which script? the one referenceing or the one being referenced?
Whats the advantage of Slerp over Lerp for rotation? I'm looking at an example for something like a turret aiming at a target and it uses slerp. Is it less buggy?
the script with the credits field. why put a method on the script referencing it when it cannot access the field in the first place?
it's in the name: Slerp is spherical, Lerp is linear . . .
so its just changing the speed how it smoving?
_credit.credits
Slerp is better if you need to rotate a direction vector
like an animation curve
thanks! :D
it does do what its suppsoed to to but sometimes... isInvincible doesnt catch on as quickly?
why is that exactly?
It keeps the vector normalized (because it's spherical), and it will actually make the rotation feel linear. If you used regular Lerp, you'd see a slight acceleration towards the middle point of the lerp
Because you're setting your IsInvincible depending on the animation (I wouldn't), I would look at how quickly this happens... it looks like maybe its too slow to be invincible == true, so you get damaged twice
ahh thank you
Would you ever use Slerp for velocity movement?
anyone know why this happens, Im new to coding and have no idea
What's a Monobehaviour
Is your VS/VSC configured too? !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
Idk, a tutorial told me to use it
Did it? Show the tutorial
see how yours differs
I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 156
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-4-10
oh great philosopher, look at what they typed carefully . . .
This code does not have Monobehaviour anywhere in it
i changed the logic to simply setting the variable to true when the animations bool parameter would be true and it setting to false as animation event, but i still take 2 dmg instead of 1
It does???
Where?
The 4th line
follow the stack trace of the bools, see where the code trail leads
hint: it does not . . .
im baffled
No, that says MonoBehaviour. Where are you seeing Monobehaviour
Monobehaviour
MonoBehaviour
Are these the same?
Big hint. As with most programming languages, c# is case sensitive
Monobehaviour
MonoBehaviour . . .
Im slow, sorry
1- MonoBehaviour is already present in a new script
2- Typing it should autocomplete from your IDE...
Either your IDE isn't setup, or you ignored it.. but why you changed that in the first place?
I have no idea, i just typed, i didnt know the language was cap sensitive, but now i do so thank you
MonoBehaviour is already there when you create a new script. there is no need to type it manually . . .
I deleted everything and followed the tutorial, I wasnt paying attention to it being there
π ±οΈ is for baffled.
also, following a c# beginner course would have mentioned the language is case sensitive . . .
following a tutorial and not paying attention doesn't bode well, my friend . . .
Would brackeys have been a better idea?
you would have made the same mistake
Brackeys is usually not a good idea, no.
im following a tutorial for an addon i just bought and he uses this line in his code SceneManager.LoadScene(0);
but it gives me an error
error CS0103: The name 'SceneManager' does not exist in the current contex
is there something i need to install for this to work
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHealth : HealthManager
{
public float health = 100f;
public override void TakeDamage(Vector3 location, Vector3 direction, float damage, Collider bodyPart = null, GameObject origin = null)
{
health -= damage;
if(health < 0)
{
dead = true;
health = 0f;
Debug.Log("DEAD");
SceneManager.LoadScene(0);
}
else
{
Debug.Log(health);
}
}
}```
is it underlined red?
no
!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
Configure your IDE correctly ^
It would have auto added the thing you need for it to work
how do i set new instance of float like ("cam.senX = new float ????") what comes after float i cant seem to understand why and what
float is not a reference type
you don't create it with new
You just set the float to the number you want
then how do i get a intance of a float ?
unity gives me error
You don't. floats don't have instances
i am using float values across scripts
they just are
what error
you have misspelled the function name. I wonder about all those people who were looking at something deeper. You call BuildPhaseToAttackPhase but your method is actualyl called BuildPhasetoAttackPhase (ouch... I guess I'm few days late to the party) sorry ))
let me send to you wait
i dont really understand it
i am new
Something on that line is null but you're trying to use it anyway
the first person helping at the time pointed that out, but tried making Zac think about it for themselves
π
nv mwrong screenshot
That can't be the line. Show the full !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.
ok
oh... okay okay. So the person who did that thought that the person who got this error went to this channel very next second and haven't gave it few thoughts?
https://hastebin.com/share/umaduzenuh.csharp this code got the error in
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Reasonable. I also always rush to this channel the very second my console throws and exception. Should prolly write some api for this. As soon as exception is thrown, send a debug code to this channel
I've no idea what he was thinking... however, the majority of people do do that.. and it's better to teach people how to think rather than spoonfeed the answer
Okay, so, the lines of code you sent aren't even in this file. Why did you think it was on those input lines?
cam is null
cam is null idont get it
Where do you assign cam
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
cam code
agreed. thinking is critical. critical thinking, we call it . . .
even better to send them to read documentation π
No, on the Pause script. Where do you assign the variable cam
bold of you to think people will click a link π
or read anything if they do? π
what if i call the is animation playing in the if statement each time, wouldnt it be forced to check it at that moiment every time, providign a correct bool value?
cam = GetComponent<PlayerCam>(); i get the component how do i assign it then ?
yeah I checked the documentation, still have no idea... wait, I had to read it all thru? Really?!
do i public it ?
So, you're assigning cam to the PlayerCam script on this object. Does the object with Pause on it also have a PlayerCam script on it
It was already checking the animation every time anyway, you'd just be moving it to somewhere else .. wouldn't make a difference
is there a way to find instances of my code like where a certain function is called across all scrips not just the one you are currently editing
no i dont think so how do i apply player cam script on it ?
probably worth using the search function of your VS?