#💻┃code-beginner
1 messages · Page 729 of 1
i use vsc
It usally gives u a hint when Theres an Import missing
Iirc u need to import but i might be wrong
Lemme See rq
you need using System.Collections.Generic; iirc
thank you
Yes that one
vscode should definitely tell you about that though
Yeah
There should be a light bulb or Something in the line
But for unity i dont use vsc Just rider
Nice
Yep that one
after a few years you just remember the namespaces
ive only been doing unity for a month or something now rip
thats what IDEs are for, they help you out
now it's getting mad about my right click input callbacks
what is it saying
i think it's a null reference
usually helps to share the error 😆
but idk what would be null
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
oh
oh shit i know what i did
the coin script is in the child of the prefab it's instantiating
tbh imo its easier to get rider community edition cuz it has good support out of the box
i need to get the child for that stuff
you can use GetComponentInChildren<>() to get components from children
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Component.GetComponentInChildren.html
do not find things with game object names
if i ever do this i would like to personally request the council of robs to beat me with a hammer
As a fellow rob I will 🔨
alright
i can place the coins and shoot them with my triangle
i shall save giving the coin physics for tomorrow
and for when i have added some test dummy enemy thing with infinite health
and i'm thinking about making it so that you have more force when throwing it more horizontally but i'm not sure what i should use to do that
thankfully i'm in 2d
but if you've ever played ultrakill it's like that
2d is kinda just 3d but orthographic and everything is planar
unity is just strange
yeah
Thanks. It's looking good, but I'll finish writing it tomorrow
it's just for counting the damage so I can see when it has dealt enough and end it
Trying to make a main menu, and I already have the UI's setup with separate Canvas's for pages and all that... I even have a "First Selected Button" setup as well for when a Gamepad/Keyboard is last used.
However I am struggling with how to make it so button pressed = activate new Canvas and de-activate the other one.
did you actually mean to do (int)(EffectDuration / EffectFrequency);?
isn't that the same because of /?
no
my example casts the result of /
instead of casting EffectDuration to int, then doing /
oh then maybe actually
Do you want it to return int?
Seems like this is a timer. Float would make much more sense for a timer.
well my thinking is life points are always int and damage is always int so to count damage I should count in int
no I want to count the total damage dealt
the damage per interval is EffectPower
and the interval is EffectFrequency
ig I should call it EffectInterval
The better way to design it would be apply X damage every Y seconds Z times
well I'm basically calculating z dynamically instead of having to pass another variable
yea but there will be inaccuracy if you want to ensure some amount of damage is always applied as an int
anyway your choice
If I have some ability with a cooldown. Is using Invoke ( allowAbilityAgain, cooldown time ) bad practice?
Why do I see often online timeSinceThing += Time.deltaTime
the ability would have a duration, and you just count the time until you reach the maximum duration
Somewhat. Invoke uses reflection which is slow and error-prone if things change names, and once started can't be stopped. A manual timer in Update lets you conditionally tick time, pause or unpause individual timers and generally just have more control over when stuff happens.
Yes for sure. Thanks for knowledge guys. So we are just += the time then lol 😆
There's basically three ways to handle timing things and they're on a sliding scale of convenience versus flexibility.
On the easy-but-inflexible side is Invoke, on the total-control-but-kinda-annoying side is a manual timer in Update, and in the middle somewhere are coroutines
(dont forget async!)
this should do, I can just return that from a method and use it to start a coroutine timer right?
sorry what are you returning?
the IEnumerator
Like, “do ___ when coroutine ends”?
hmm im not sure if you are doing something good
uhoh
StartCoroutine(DealDamage()) is the ideal way to start it
How do you plan to start it?
https://paste.mod.gg/pytygrcahtqo/0 this is the BurnEffect Class, which is not a Monobehavior. I was planning on passing the Effect to the EffectController, which is a MB, so it can start the timer for the effect
A tool for sharing your source code with the world!
I dont see how that function is called from this
is there something in Effect? did you mean to have some virtual function each effect overrides?
No Effect is just the abstract class. StartEffect creates the BurnEffect and sets its properties and returns the BurnEffect. The BurnEffect contains the IEnumerator. The EffectController calls StartEffect and receives the resulting BurnEffect. It adds the BurnEffect to the EffectList, and starts the timer for it based on the IEnumerator in the BurnEffect.
That's the plan anyway
yea but how do you plan to start all effects?
public abstract class Effect
{
public abstract IEnumerator StartEffect();
}
something like this?
I have ```CS
public abstract class ScriptableObjectEffect : ScriptableObject
{
public abstract Effect StartEffect(EffectContext context);
}```
and
public class Effect
{
public int EffectPower;
public float EffectDuration;
public int EffectInterval;
public int EffectRecurrence;
public bool EffectIsDebuff;
public int EffectAuthorityLevel;
}
actually the Scriptable Object class is abstract, not the Effect class, mb
oh i see there is a so for each effect too
yes
but again how will the coroutine be started correctly on a mono?
void useMagicWand() { all nearby enemies.effectReceiver += new BurnEffect(params) }
one option
I'm thinking I can pass in the mono from the EffectController and start the timer on it in the BurnEffect, or I can return the IEnumerator to EffectController so it can start the timer there.
nearbyEnemy[i].startEffect(magicWandBurnEffect)
and when I did the first option people yelled at me
yeah creating new stuff at runtime is not efficient
having stuff pre-configured and then “turn on or off” / “react to float value” is quicker i think
oh no i allocated a new class instance the world is over!!!! /s
there are a lot of different effects, its not really practicable I think
Modularity can still be intact. Youre using polymorphism already but
I’m just letting you know I had huge issues with the new keyword
its fine unless done too much all the time
If so then you think about alternate designs to reduce allocation/gc
Guy’s making an MMORPG no?
I suppose I could construct the IEnumerator in the controller from the variables in the effect instead of returning the IEnumerator
you dont construct it
It just seems like, it should already be there
well I have to give it the variables
if you do IEnumerator e = StartBurnEffect() all you did is execute it once and its now yielded forever till called again
plz dont "return it" because that is just incorrect
well I mean
you can do Func<IEnumerator> e = StartBurnEffect; and pass around a func reference of it to start later.
I thought that was obvious, mb. I was gonna use StartCoroutine(DealDamage()); to start it
You can use SOs for that, or per-enemy-instance member variables / functions to configure those
I wanted to point this out but I am tired 😆
thats good but words mean specific things in programming land
I’m just saying there’s so many paths to take avoiding creating new stuff at runtime 🔥
which is a pointless micro optimization unless you actually have issues with creating new stuff at runtime. At which point you should use the profiler to determine what the real issue is. A short lived effect, not even created nearly once per frame, isn't gonna do shit to your performance
the issues you had with new don't suddenly mean to avoid it for no reason. theres a time and place to avoid it in favor of stuff like pooling
you cant always avoid creating new stuff at runtime
Because that is literally the component that calls the OnTrigger functions
Just to be curious is this one of those lines that is thought to be "best not to use often" or it's an easy "finder"? I know it's not an issue if you don't have a lot but I'm just practicing best methods as I can 😛 GameObject.FindGameObjectsWithTag("Dreadnought").Length
@polar acorn
In general you should try your best to avoid any function with Find in the name
Are you actually using the rigidbody to move the object
I was thinking about just incrementing a variable each time a thing is spawned and decrement it any time I destroy it
but might not be entirely perfect (mostly because I am sure I'll forget where all those are to do it hah)
I have it in object but code doesnt work
Show how you're moving the object
If you want to keep track of a bunch of objects that get spawned in, you can add them to a list as you spawn them
And remove them when they're destroyed
Not move
If nothing is moving, then, by definition, a collision cannot occur
When i touch it its doesn't destroyed
Ah ok adds it in his brain to another possibility lol
How are these objects touching if neither one is moving
Its move but i stop this line
Couse i stop movement
You can see it in code
So is an object moving or not, you're giving me directly contradictory answers
No ane code above you can see it
Which of the two objects is moving, and what is the method by which you are moving it?
overlapping without moving doesnt trigger?
Trigger events are called by the rigidbody whenever it attempts to move. If two objects are overlapping and neither one has any forces acting on it (including gravity), it won't register a collision
Well, you could explicitly call WakeUp on one, but until some force occurs on a rigidbody it won't be sending any messages
interesting
Aaaa player should touch tag coin
Then its destroyed and happen what in code
I'm just going to repeat my question until you answer it
Which object is moving, and how are you doing the movement
Brroo
You see code right?
What code
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
Put it in a format that's actually readable
- Your movement is commented out. This means the object is not moving and therefore cannot have a collision.
- Your debug log is inside the if statement. Try logging the tag of the object you hit before the if statement to see if it's detecting any collisions at all
And in the future, use a bin if it's gonna be two pages of vertical text
No I made the item fall on him from above.
So it's moving by gravity
Yes
When I said "how are you moving the object" you could have actually answered that
and said "gravity"
instead of pointing to code that is not doing the movement
and saved us both a lot of time
I thought you meant the code I stopped.
But ok
By mistake
Whats wrong now?
Now you put the log outside the if and see if it's detecting collisions at all
how it will work Without a run command
What
can you send code what you mean?
Put the log outside the if
and log the tag of the object you hit
I made log to know if coins touched
because right now you only get a log if you hit something of a specific tag
so if I put it out how it will work
Hi, any idea why it happens on a prefab?
Prefabs cannot reference objects in scenes
Prefabs can exist anywhere. Scene objects only exist when that scene is loaded
You'll need to set the variables after spawning an instance of it
Okay, so how do i make it work when the prefab clone enters the scene?
Assets can't directly refer to Objects in Scenes, but their instances can be configured with those references.
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "coin")
{
scoreValue += 1;
score.text = scoreValue.ToString();
Destroy(gameObject);
}
Debug.Log("Coin collected! " + scoreValue);
}
?
Use the CompareTag() function btw
and should work without if
Sure but instead of logging something unrelated, log the tag of the object you hit
so if it logs anything you'll know what thing you hit
and potentially why it wasn't working
which you know?
Debug.Log(other.gameObject.tag)
Debug Log will print the thing you pass in. If you want to log a thing, you pass that to debug log
You know how to get the tag of the object you hit, you're already doing that
so, log it.
Looks Like the tag
This destroys the current object if a coin collides with it. Is that what you expect?
Also share !code properly
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
we already told him three times
Gotta keep telling until they get it.
i dont know the correct way to write thats trigger is tag player
do you want to destroy the coin?
i think its small lines to make it as code?
yes
Also something that was bothering me for a while, but if your English is not very good, use translation tools. It's very difficult to understand what you're trying to say.
the taged player
So it sounds like it's being detected just fine. If you didn't get the log before, then the object's tag is not "coin"
It could be "coin " or " coin" from the looks of things
but any way its should work if any thing tuch it like that
Even if it's small, you need to put it in a snippet - cs code
Again, that could very well be coin or coin instead of coin
you want to destroy the player when you touch a coin?
destroy coin when player touch
in code or unity tag?
the coin is other.gameObject, gameObject is the player
youre destroying the wrong thing
anyway no thing is destroyed 🙂
then change tag to player?
first make sure the tag on the coin object is spelled correctly, without extra spaces before or behind coin
put your mouse cursor into the text field where it says coin and delete empty space if there is any
not there, in unity
private void OnTriggerEnter(Collider2D collision)
{
if(collision.gameObject.CompareTag("coin"))
{
Debug.Log("working")
}
}
should be this, no?
I don't remember where to see the tag manager
If U add a new Tag iirc
click add tag
looks like you can't actually check if there's an extra space at the end
you just have to delete and readd
how should i find space?
try removing coin and adding coin again, without space
Don't do bad code to cover up worse mistakes
Ik
bro im still tryingto know how this languge work
CompareTag is literally designed for this problem
it'll tell you if the tag you want doesn't exist
It'll give you a warning in the console
Then use compareTag
wouldnt it be fine since its just temporary?
anyway now is there any issues in code or try rewrite the tag?
There's nothing more permanent than a temporary solution
code looks like it should be fine other than destroy, but using CompareTag would be better
Ye ik i was joking, also i mentioned compareTag before
See
@mighty peak
try this and see if u get the debug message
same
Wdym same
ok replace the == with CompareTag method like people are saying
wait
What
remote session end wait 🙂
are we talking to a chatbot?
no
im using remote desktop so
I think google translate is just pretty bad at arabian languages
Oh okay
he told me to move it outside 🙂
bro my english not that bad
Okay
so make debug back in if?:/
Wdym
It's hard to understand sometimes. Other times it's ambiguous.
just copy paste this in script
its same what im using but just add debug
Yes and we established that the collision message is working
wait 🤷
So now try compare tag
i think we moveing in close cycle
that what i do in the first but ok
If you had it before then why did you change the code before you sent it
here its
and its should be?
if (other.gameObject.CompareTag("coin"))
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "coin")
{
Debug.Log("its work :/");
scoreValue += 1;
score.text = scoreValue.ToString();
Destroy(gameObject);
}
//Debug.Log(other.gameObject.tag);
}
oh ok
Nice
Good ig?
you're destroying the player not the coin
nothing is destoyed
but let me try something
yea thats because you're destroying gameObject not a GameObject
Ye Cuz Ur trying to access Something thats gone
The Error is pretty clear tho
You should try to understand Error Messages but that comes with time i guess
yes im tring to find where i call it back :/
Double click the Error
i hate this blocked ny sever
rrrrrrrrr
and its open that
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawner : MonoBehaviour
{
public GameObject[] spawns;
float timeBtwSpawns = 1;
void Start()
{
}
void Update()
{
timeBtwSpawns -=Time.deltaTime;
if (timeBtwSpawns <= 0)
{
timeBtwSpawns = Random.Range(0.5f, 1.5f);
Vector2 spawnposition = new Vector2();
spawnposition.x = Random.Range(-2.5f, 2.5f);
spawnposition.y = -6;
Instantiate(spawns[Random.Range(0, spawns.Length)], spawnposition, Quaternion.identity);
}
}
}
im really didnt say specific object
how i write this sht since 2 years
if i need ti make bake button down and up command for icon make it directly from code or should add onclick?
or something
Which object did you attached this script to?
im tryig to solve it no errors now but they doesnt respawn let me try destroy all
now its destoyed but doesnt respawn
void Update()
{
timeBtwSpawns -=Time.deltaTime;
if (timeBtwSpawns <= 0 && spawns.Length >= null )
{
timeBtwSpawns = Random.Range(0.5f, 2.5f);
Vector2 spawnposition = new Vector2();
spawnposition.x = Random.Range(-2.5f, 2.5f);
spawnposition.y = -6;
Instantiate(spawns[Random.Range(0, spawns.Length)], spawnposition, Quaternion.identity);
}
}
}```
Hey, Im very very new to Unity and C#, but Im kinda struggling a lot with refrencing game objects in scripts, for example, lets say I have a player, and I want them to enter a trigger box to teleport across a river, I wouldn't have the slightest idea how to refrence the trigger box.
also, please don't forget about G NOUR's problem*
you don't need to have a direct reference for that, you would use something line OnTriggerEnter which provides the reference to the other object
its ok im trying to soolve it:)
but can i get some help ? 🙂
pay attention to the warnings in your IDE
so would it be a "OnTriggerEnter" then a line of code moving the player?
sure, if that is how you want to do it
or?
Are there any console errors?
You can't compare a number and null.
why are you intentionally leaving a condition that always evaluates to false in your if?
i dont think thats what i want
i just need it if its less that 5 or null and if times ends respawn again bettwen 0.5 and 2.5 seconds
What does it say in the detail area?
where is this area?
an int can't be null
the issue is perhaps the 999+ errors you have
Hey, i started with create with code
which int?
perhaps the one your ide is highlighting?
buddy there are tools here to help you
put some effort in
huh 🙂
you mean change game object (spawns) to int?
so its wont be null
and how should i make dont be null 🙂
https://docs.unity3d.com/6000.2/Documentation/Manual/Console.html
The bottom section (D)
it's already not null
i know its console not detail area but ok
the entire window is the console
aaa its gave me same null errors also
the detail area is part of the console
check the thing that's actually null instead of some random value
put some thought and effort into this
don't just stumble around randomly hoping itll work
all object is
when its up to 7 y destroy and after destroy if be null or > 1 spawns
but thats what happened
Alright, someone tell me how I screwed this up. The OverlapCircle line stops the spawns. The circle is pretty small, I checked. 😛
Alright, I'll simply tell you it straight.
You've got a null reference exception because you've destroyed something that you're still referencing.
We need to know what object threw the error. Which line. Why was it destroyed. If it's a prefab or scene object. Etc.
i think thats answer
if you have determined the issue to be caused by the overlapcircle then you'll need to debug that. start by drawing the circle, make sure gizmos are enabled and use Gizmos.DrawSphere or a library like this one
then you should see what collider(s) the circle is over top of
I had a collider on that spawner. SMH.
guys please reply me when the massage is for me 🙂
Why is it that the obvious answer comes to you after you ask even when you've tried for hours to figure tha tout
lol
i dont know which one you talking about
life cycle
try to learn
so what now?
im reached to close wall
I'm a newb but my guess is check if it exists before you reference it
also, I do wanna ask just for clarity, how would I call on a spesific game object if I needed to?
Choose the best way to reference other variables.
Need more info
#💻┃code-beginner message
#💻┃code-beginner message
Here
New bot can't do commands inside of other messages
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
Im really need it
Oh
I think you say make new bot add entire code for normal code
Why do you need it?
Its for coins
And im talking about squares
You should really use Google translate or something...
🙂🙂
No just can't read more🙂
Need a break 😂
It's not just read. It's write too.

We end up needing to guess what you mean half of the time...
You could've probably solved this 4 hours ago.
Stop doing random solutions.
Show us the object and script that calls Destroy.
It's your script with the TriggerEnter2D callback method.
Show us the details pane for the console error.
As is, I'm assuming you're referencing scene objects and cloning rather than referencing an asset-prefab
This is not very inviting to help you
Yo
Trigger enter is for players touching coins ok?
Leave it
Here is for squares
Those
Which you can see here
And after run be like that
Alright. My last response since you're unable to understand the problem. You're referencing something that you've destroyed during runtime. You need to figure out what object has been destroyed. Not "leave it" alone because it isn't throwing any immediate errors.
Good luck.
And Same thing if i delete == null
Bro I destroyed the squares also when it up to 7y
And i deleted coins from respawns for that's
So that the player does not take it and another problem occurs now
Hope you understand now why i said leave it i already deleted it from respawns
And my other issue is i don't need it to be like that just when squares be less than 5 respawns 1 more between 0.5 and 2.5 sec
You're wasting my time. Don't message me anymore please. Thank you.
I left a while ago. I'm not dealing with like five layers of translation either way around
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Can someone tell me what this does?
public static void Shuffle<T>(this IList<T> ts) {
var count = ts.Count;
var last = count - 1;
for (var i = 0; i < last; ++i) {
var r = UnityEngine.Random.Range(i, count);
var tmp = ts[i];
ts[i] = ts[r];
ts[r] = tmp;
}
}
I know it shuffles, I just didn't know what every individual line of code did was all
that explains the algorithm being used which should make it clearer what each line is doing (especially since each individual line is incredibly simple)
Okay I'm sorry, just found out I had ADHD so it's kinda hard for me to understand haha
BRO that is not how ADHD works bro
And I had it since I was born
If there's a specific line you're confused about, you could probably ask about that particular line else I would advise you to go at it one line at a time and ask what you're not understanding about that particular line.
Doesn't seem Unity specific though so you're probably better off asking the csharp discord server
There's no command called
csds.
Well considering I have issues understanding and looping thoughts 🤷 but this isn't the place
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
It's fine to ask questions about syntax if that's what you don't understand, but make sure to go through the C# documentation before that and only ask about concepts that the documentation does not clarify.
Can anyone teach me unity?
youtube
You've already been provided with a link to Unity Learn. This is not a place to solicit a tutor.
Kk I don’t want to be muted again:(
@chilly elm I think you do. As it has been made abundantly clear to you that there's no off-topic on the server. Consider this is a last warning.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
me and my groupmates are working together for uni so im commiting a empty project so he can clone and also work on it, but the packages folder is like 200 mb
is the best way to go is just me sending him the project as a zip and then commiting only stuff we add in the assets folder like scripts sprites etc?
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
oh ok lol ill look at that thanks
i think i have a runtime error in my code but i don't know how to find it. i can't share my code bc i'm at school right now and discord is blocked on my laptop
can someone help, or am i being too vague?
i made a function that gives a coin access to a list of other coins to find the closest one and trigger a redirect function when shot
but shooting a coin freezes the editor and crashes unity
You have an infinite loop. It's usually caused by having a while loop that doesn't end
ok
wait i think i might have found it
but i'm not sure how to address it
i have the foreach loop to determine the closest other coin, if a ray can be cast without hitting a wall between the two coins then the same function is called on the other coin
it's recursive and ends when the list has no more coins that can be hit
so why is it breaking with only one coin active?
well is the list being changed?
consider flattening it out to have it not be recursive
each coin is removed from the list to avoid being compared with itself
i'll see if i can copy it into an email draft to post here
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
void RedirectCoin(GameObject otherProjectile)
{
SlingerCoinScript closestCoin = null;
float closestDistance = 0f;
slingerScript.activeCoins.Remove(gameObject);
foreach (var coin in slingerScript.activeCoins)
{
SlingerCoinScript otherCoinScript = coin.GetComponentInChildren<SlingerCoinScript>();
Vector2 coinVector = currentPosition - otherCoinScript.currentPosition;
RaycastHit2D hit = Physics2D.Raycast(transform.position, coinVector, coinVector.magnitude, LayerMask.GetMask("Surface"));
if (!hit)
{
if (closestCoin != null)
{
if (coinVector.magnitude < closestDistance)
{
closestCoin = otherCoinScript;
closestDistance = coinVector.magnitude;
}
}
else
{
closestCoin = otherCoinScript;
closestDistance = coinVector.magnitude;
}
}
}
if (closestCoin != null)
{
Debug.DrawRay(transform.position, closestCoin.currentPosition - currentPosition, Color.blue, 2f);
closestCoin.RedirectCoin(otherProjectile);
}
else
{
Destroy(otherProjectile);
}
Destroy(gameObject);
}
ik how to do it, i just can't post it from my laptop
if any clarification is needed on some parts please say
oh so it isn't recursive?
i thought it could be considered recursive
but no, i suppose
i don't know where my code would be looping infinitely
i'm using finite loops and it shouldn't be calling the same function in other coins when there are no other coins
i feel like it being "recursive" doesn't really solve anything
you could just have a nested loop in whatever slingerScript is
i might not be clarifying well enough
slingerScript is the script that contains the abilities of the gunslinger character i'm making
throwing a coin to shoot is one of his abilities
shooting a coin makes it look for the closest coin to bounce to and trigger another redirection
but when i shoot the coin, unity crashes
presumably a runtime error
Editor logs
Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log
Unity Hub
Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs
i understand this though. and my statement doesn't change - this could just be flattened and put into the slingerscript
Hello all, I'm having some difficulty getting a weapon switch script to work, it should be tied to the scroll wheel and it was actually working yesterday but for some reason it's returning null due to the object reference not being set. I would apricate any help :)
using UnityEditor.Rendering.LookDev;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
InputAction scroll;
Vector2 scrollPosition;
void Update()
{
scrollPosition = scroll.ReadValue<Vector2>();
if (scrollPosition != Vector2.down)
{
scrollNumber++;
}
if (scrollPosition != Vector2.up)
{
scrollNumber--;
}
if (scrollNumber == 10)
{
scrollNumber = 0;
}
if (scrollNumber == -1)
{
scrollNumber = 9;
}
}
}```
The error will tell you which line has a NRE. Read that line, work out which object hasn't been set ... make sure it's set before trying to use it
Gonna assume it's scroll that hasn't been assigned
The line is scrollPosition = scroll.ReadValue<Vector2>();
Yeah, scroll is null
Why is that? It should be reading the value from the input system no?
because you haven't assigned anything to scroll
This
InputAction scroll;
Declares are variable called scroll of type InputAction ... it's an empty box until you tell it which instance of InputAction to use.
Urgh my discord is now playing up
My guess is that yesterday scroll was public which means it was being created and serialized in the editor.
Right there we go I can talk again That makes sense, so how would I go about assigning something, I believe it should be something after InputAction scroll but I am stumped as to what
Either make it public and set it up in the editor or you get the reference from an InputActionReference or InputActionsAsset
= is for assignment.
This is strange as I've never had to do this with any other input action
Again, were they public before?
The only way it would have worked is if they were serialized/public or you assigned them
Nope, not as far as I'm aware. I have swapped it to public which has cured the error message but it's still not reading the vaulue
What you're describing doesn't make sense, you can't just declare a random variable and it magically knows what bindings and action type etc you want
If you're confused you need to go back to your other ones and look what you did because it certainly wasn't this
Agreed, I think I've just found the issue. Let me test and get back to you
Ok
Alright, this is what I've just tried and I'm still getting the same error ```using JetBrains.Annotations;
using UnityEditor.Rendering.LookDev;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
InputAction scroll;
Vector2 scrollPosition;
public int scrollNumber = 0;
void Start()
{
scroll = InputSystem.actions.FindAction("Weapon Switch");
}
void Update()
{
scrollPosition = scroll.ReadValue<Vector2>();
if (scrollPosition != Vector2.down)
{
scrollNumber++;
}
if (scrollPosition != Vector2.up)
{
scrollNumber--;
}
if (scrollNumber == 10)
{
scrollNumber = 0;
}
if (scrollNumber == -1)
{
scrollNumber = 9;
}
} ```
if scroll is still null.. then your assignment in Start() is failing to find the action
I feel like I'm going insane, this is the InputManager that I have set up. As far as I can tell the action that I've listed for the scirpt to find is correct.
If you do not have any other script handling your input system, you need to create a reference to it on start before using it.
inputActions = new WhatEverYourInputActionsetIsCalled();
inputActions.Enable();
Reading now :)
could i make a raycast call OnTriggerEnter2D? if so then that could stop me from having to use a recursive function
i thought it would be controlled but apparently not, i commented it and my game stopped crashing
I am having a hard time getting what you mean exactly.
hold on
it'll take me a while to share a video or picture bc i'm on school wifi
basically, you know how ultrakill's coins work?
i have a list of coins that the player can shoot, shooting one coin causes it to look for the next coin and makes that coin look for the next
i've done this with a recursive (?) function but it freezes and crashes unity
idk what's going wrong with it
My guess is that slingerScript.activeCoins.Remove(gameObject) doesn't remove anything, especially since the coin component is retrieved with GetComponentInChildren. Which is why nothing gets removed from the list so it just goes through it indefinitely
Use a debugger to step through the code and see what it actually does
If that's the reason then slingerScript.activeCoins.Remove(GetComponentInChildren<SlingerCoinScript>().gameObject) probably fixes it. But that's just a quick crutch to verify if that's it
If the only use for the activeCoins list is this method, change it so that it stores these objects directly instead of objects that have the SlingerCoinScript component
germans here ?
This is an English speaking community.
ahh okay thank u
im sure many germans speak english!
I'm guessing he doesn't
Hi, I'm making a farming game for a college project and I'm currently having an issue where because my FarmManager gameObject is dontDestroyOnLoad it's being carried across scenes but it has properties that are tilemaps on a certain scene. When I switch scenes the farmManager is being carried across scenes because its dontDestroyOnLoad but the tilemaps arent. I've tried making my grid object, which is the root object for my tilemaps, DontDestroyOnLoad but when I do that it gets duplicated and breaks my game. Ive tried using a singleton pattern to fix this but it doesnt seem to work. any advice? thanks
Below is the PersistentObject script that I'm using to make the grid DontDestroyOnLoad
public class PersistentObject : MonoBehaviour
{
private void Awake()
{
GameObject rootObject = gameObject;
if (rootObject != null)
{
rootObject = gameObject;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
}
gameObject is the gameobject this mono instance is attached to. I dont think it would ever be null when Awake is called.
You are doing the singleton pattern incorrectly if this is an attempt of that.
So what is it that you want to happen here exactly?
Having a DDOL object with persistent references to scene objects isn't a good idea. You need to change the pattern. But you'd have to explain what the code is actually doing or trying to do for more specific help.
But yes your Singleton implementation is definitely wrong
Im trying to make it so when the my farmManager gameObject is carried across scenes the properties it has that are tilemaps arent removed so when you go back to the farm you can still plant crops etc.
Thanks ill have a read
ObjA.Awake
ObjA.OnEnable
ObjB.Awake
ObjB.OnEnable
Is this correct order of execution? OnEnable runs immediately after Awake for each object, meaning I have to do something like:
void Start()
{
Player.Instance.OnDamageTaken += UpdateHealthBar;
}
void OnEnable()
{
if(Player.Instance != null)
{
Player.Instance.OnDamageTaken -= UpdateHealthBar;
Player.Instance.OnDamageTaken += UpdateHealthBar;
}
}
void OnDisable()
{
Player.Instance.OnDamagaTaen -= UpdateHealthBar;
}
This way I am guaranteed to subscribe to Player object event?
Start works because Player Instance will not be null since its set in Awake, but I cant use OnEnable as it will only work if Player happens to instantiate before my other object.
if you have Singleton setting up in Awake its possible you will have it null by this OnEnable
no guaranee unless you change order of scripts or just do
Start() Sub
Destroy () UnSub
But I have to do OnDisable UnSub, hence the above
Afaik subscribed event will throw an error if the object is disabled?
Sub in OnEnable, unsub in OnDisable - if you're toggling the active state
OnDisable is guaranteed to run even if the object is destroyed right? It runs even when I exit the playmode
yes OnDisable -> OnDestroy
Yeah but to guarantee it(without using script execution order) I have to do extra step in Start() to sub
that's one way, not the only way
idk I find it easier to just have the singletons have a slightly early execution order
I could start with object disabled too hmm
So you set singletons in script execution order?
I just change them so they run earlier so they are ready for other scripts OnEnable
is considered bad practice / iffy design but it depends
I might give it a go tbh, it does sound like a good idea
I just need to make sure not to write too much spaghetti
why do people keep wanting to sub and unsub to events with enable/disable
It's best to try and avoid changing the script execution order
Afaiak its a good practice
To make sure you dont have any leftovers
but i keep seeing people sub on awake/start but unsub on disable
why wouldn't you?
If you toggle it off.. and then back on..
That is wrong imo, you need to cover all cases I think(awake/start + onDisable)
If it was me id just have my subscription check enable state instead of unsubscribing
if you disable and enable object then yes Start/Disable makes no sense cause if you re-enable you have no sub anymore
Probably would just use additive scene loading for this TBH
Why does FarmManager need references to tilemaps anyway though
private void Start()
{
PartyController.Instance.OnMovementSpeedChange += UpdateMovementSpeedText;
}
private void OnEnable()
{
if (PartyController.Instance != null)
{
PartyController.Instance.OnMovementSpeedChange -= UpdateMovementSpeedText;
PartyController.Instance.OnMovementSpeedChange += UpdateMovementSpeedText;
}
}
private void OnDisable()
{
PartyController.Instance.OnMovementSpeedChange -= UpdateMovementSpeedText;
}
Would you consider this a good practice in general?
Ignoring the purpose of small text change which could be changed to update more things(or even done in Update)
Are there better solutions for updating UI? We've had similar talk before and I thought that using events makes sense to keep UI and logic separate.
This is just 1 text to update, but there will be much more(either 1 event per text field or general block of data or 1 event for all relevant UI like player stats)
For example I could update whole inventory this way or only 1 inventory cell(as an item is moved/added/removed from specific cell)
events is good practice.. just do onEnable and onDisable then.. no need for Start. change the singletons to init earlier and its a non-isue
In this example the above class would never be a singleton as it's purpose is to subscribe to what it requires right?
What about naming? The above class is called something like "WorldUIController", but it's not a singleton while PlayerController is a singleton.
I might have messed up the names a bit 😄
Should I just call it WorldUI? Since it's not sending anything outwards, just receiving events.
Singleton should be reserved for like Manager type of objects usually
What would you say the difference is between managers and controllers? Would both be monobehaviors?
idk thats just semantics
Is there something I can read up on standard namings for such things?
Controller generally, when it controls something specific. Like ChracterController Animation Controller etc..
Manager is when it takes care of multiple systems , Game Manager, UI Manager etc.
Controlls something directly?
makes sense
Directly as in with a direct calls, not events
its just naming for sake of own organization , there isn't like a set book or anything
There should be something tho
they got c# naming conventions , and I think unity has some general gaming jargon ebook
Organizing code is pretty big topic imo
yes which is why its usually done to whatever standards you setup, as long as they are consistent
I did some research and I am doing better than before.
The best change I made is to organize scripts by their purpose instead of type(or however it's called)
like people normally name a singleton Instance
i've seen places (even in unity) where they name Singleton instead
Meaning all player scripts go into Player folder(including UI related to the player as well as scriptable objects and assets/sprites)
I have a very basic question, Im trying to make a scrip that resets the position of the player when a BoxCollider2D meshes with another BoxCollider2D. but, despite making the collider box a trigger, and coding it with both OnColliderTrigger2D and OnTriggerEnter nether are giving me results
public class FallScript : MonoBehaviour
{
public GameObject Player;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnCollisionEnter2D()
{
print("worked2");
Player.transform.position = new Vector2(0f, 0f);
}
}
*wrong script sorry
1 of the colliders needs a rigidbody for collisions to work
That's crazy 😄 I always saw Instanace but Singleton feels weird, isnt it like a keyword in some languages?
follow the link nav sent - but also, at a guess, your Visual Studio isn't setup correctly either.
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
not a keyword but "Singleton" is a pattern name that exists outside of c# / unity.
oh wow wtf is this lol
I know, but I thought that some languages have Singleton keyword similar to C# having class
maybe not hmm
its a step by step that will help you debug your issue
wow tysm
oh no idea.. if it does must be custom or something
oh yeah Unity.huh is quite good, I need to use it more often myself instead of relying on chatgpt(which I feel got really stupid, even tho I am not using it that much)
ofc its only gonna get stupider with the more bad recycled code it learns on
true
Worked, tysm
to keep a link between an effect Object and an associated timer coroutine, would it be best to keep them in a dictionary or a list of lists or arrays or similar?
uhh wasnt this solved/ discussed already a while ago?
no I'm redoing the whole system
wasnt the overall thing to just keep the Coroutine stored on the effect that wants it run ?
yes but I'm no longer doing that because the effects are not monobehaviors
yes but you can Start Coroutines on ANY mb
I passed the mb from the effect controller into the effect at first and everyone yelled at me how bad that is
you can keep the actual IEnumerator method in pocos too as long as StartCoroutine is done on a MB
other way around tho
You want to Pass the effects coroutine in the Effects Controller to run it
assuming effects controller is MB ofc
hey i plan to have my html game build differently depending on the user's platform
if i understand right preprocessor directives, #if and #endif's are the way to do it?
also if needed you can store coroutine / StartCoroutine in a Coroutine variable
yea
I did this before, where DealDamage() is the IEnumerator cs coroutineMono = mono; coroutine = mono.StartCoroutine(DealDamage());
but that starts it right away
where mono was the MB I passed in
then make it not start right away if you want that lol
thx then i have a problem
i'm missing script symbols and i can't find a solution online
could you pretty please cherry on top help me
is coroutine just the IEnumerator then?
is your IDE configured correctly for unity?
Ienumerator is how UNITY does a a coroutine yes
coroutines are not a unity concept
i believe so but i don't know how to check
i've tried rebuilding project files
they are using the IEnumerator interface to do it
I mean I return the IEnumerator to store the coroutine without starting it immediately
if you type a unity type, does it show ?
Like Rigidbody etc.
yeah thats fine , where is the issue
oh of course absolutely i'm just missing the script symbols
where are you typing it btw.
weird mine shows a lot more
i'm typing it after the #if in visual studio 2022
maybe you have some assembly defintions or something ?
what do you mean
anyone know what this error is? I can't find anything on it
assemblies , do you know them?
It's pretty clear . Agent isn't close to a valid navmesh
- not an error
- unless you are using a third party asset that makes the navmesh work for 2d then navmesh does not work for 2d
i believe they're code libraries?
I am using navmesh plus
then it's likely an issue with your setup which is specific to that asset. we don't support third party assets here
Idk if this is a direct programming question, but when I move my camera with a script, it goes blank?
public class Camera_Move : MonoBehaviour
{
public GameObject Player;
public GameObject Camera;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D collider)
{
print("Camera Move Script");
Camera.transform.position = new Vector2(18f, 0f);
}
}
it contains all the types as a unit . Anyway maybe you had assembly definition not make it show?
just an FYI - when you don't use Start and Update, remove them from your scripts. It's cleaner (especially for sharing)
i don't know - if you can tell me how to i can check
tysm
this is putting it at 0 on the Z axis as well, make sure it is far enough back from the objects you want it to see that it can render them (they must be further from the camera than its near clipping plane). it is typical to keep the camera at -10 on the Z axis to avoid this issue
(And means unity doesn’t call them for no reason)
Thats exactly whats happening, I do wanna ask, how do I set the Z then?
look in the folder of your scripts in root do you have asmdef file
use a vector3 not a vector2, transform.position is a Vector3 so the Vector2 you are assigning (18,0) gets cast to a Vector3 and becomes (18,0,0)
btw its good practice to make variables instead of using magic values (values without description)
if you ever need to change it can be done via inspector easily, instead of always changing and compiling the code every time
do you mean my visual studio solution
they meant in unity editor project window
my bad
also while you're at it can you show your solution explorer without the filters
I heard about some of thoes issues, Im still learning how to do Variables in my projects with C#
variables should def be one of the most important basics
asmdef is a type, not a file name.. search won't find it by name like that
would anyone have any clue why visual studio our of no where adding random spacing between lines for no reason. It is not a true space but a gap because i cannot put my cursor between in
ya you would need t:asmdef
it's because of that little note it adds above the directions
whatever extension you got there with [up] [w] or wjhatyever
oh alr
how do i get rid of that?
find out what extension it belongs to and remove it ?
yeah well there goes asmdef being culprit lol
not suure tbh.. did you try regen project files in unity?
unity assets dont show in visual studio
and im not sure if that search is correct, wouldnt it be t:AssemblyDefinition ?
you can also search with explorer for *.asmdef
it works but i guess there are none in assets folder
their Conditional compilations arent showing
but apparently VS is configured properly so. 🤷♂️
something obvious I'm probably overlooking?
Thanks that fixed it.
I do have another strange issue.
When ever I hit play on any game project, it would have this strange pause before fully playing. Example a character moving. It would be a delay before i can move the character then it will let me move it.
This only happens within the engine. When I build and play as stand alone this does not happen. This happens with every project 3D or 2D. I found that changing "when entering play mode" settings "do not reload Domain or scene" stops this from happening but before unity 6, i never seen this behavior before
what does "play on any gameobject" mean
you play a scene, if a gameobject is selected or not doesnt mean much
How do I call Public Variables in other scripts?
Choose the best way to reference other variables.
Get a reference to the thing whose variable/method you want and then access it with the . operator
In case anyone else somehow finds this and has the same issue, the jump in input manager was set to axis and not vector2. Thank you Carwash, PraetorBlue and joer for helping me
tyty\
how to clamp the rotation of X axis of camera
can adjust it with euler angles and simple use Mathf.Clamp on the x axis
but like when I'm moving my x axis, it's putting me back to the max value of Clamp function, idk why
transform.eulerAngles = new Vector3(Mathf.Clamp(transform.eulerAngles.x-XRotation, -60f, 60f), transform.eulerAngles.y+YRotation, 0);
likly due to the retruned angle from it being in the 0 to 360 range
you might want to do something like
Vector3 eulerAngles = transform.localEulerAngles;
if(eulerAngles.x > 180f)
eulerAngles.x -= 360f;```
to bring it into the -180 to 180 range
before doing the clamp
can u explain me the logic in simple terms that will be helpful
you are trying to clamp between -60 and 60, issue is the numbers returned by localEulerAngles are never negative
so the code above converts that 0 to 360 range to a -180 to 180 range that you can clamp
ohh
ohh
unfortunately this didn't
helped
but thanks I understood alot
that will help me find the solution myself
Modifying Euler angles this way doesn't usually work very well. Make a separate variable (private Vector3 camRotation;), change that variable instead, and set the camera rotation based on it (transform.eulerAngles = camRotation;)
how do I go about listening to an event from an unrelated instantiated object?
what does that even mean
get the object instance and sub to its event?
Normal OO concepts apply with events, they are either a member field/property or are static
I don't really have a good way of getting that instance
I guess I have to do it some other way
If you want to listen to that event it sounds pretty related
then thats the problem to solve isn't it? store these somewhere or introduce new logic so you can get the instance you want
then whatever you need from the instance can be done (including subscribing to its event)
but then I have to check every update if the object exists
then step back and perhaps we can figure out how to do this better
usually if you say want to subscribe to an event on a newly spawned thing, whatever does the spawning will subscribe OR have an event that other things can sub to so they can react to newly spawned instances.
Well if you made the component and you know what the events are then you will handle these specifically
E.g. my enemy spawner spawns enemies and I sub to the enemies OnDie event
yeah one of my effect objects is supposed to invoke the event, I could subscribe to it in the effect controller and forward it that way, but not all effect objects have an event so I should check if the object has an event before I can subscribe to it
If different effects have different events then you either handle each specially or correct the design
yeah but to handle them specially I have to check if the event exists
Otherwise inheritance is used correctly so the common base has the events required
That doesn't work
If we want to handle all effects then they all need common events and functions
thats not possible, I need a different solution then
You do or a better design
Look at Component for example, a game object doesn't need to know what types they really are, it just knows it has components with common functions like Start()
If you ask ten people you're going to get ten different designs. You need to actually sit down and chart out every single effect you are going to need and start trying to group them. Find out when things happen, which outside things it needs to know about, what could trigger these things, what kind of things these affect, and so on
yeah I know that but this is a special event from a certain effect, not something the effects have in common
Every time you ask this a different person is going to give you a different way to design this but the simple fact of it is you need to actually plan it all out.
You need to quantify everything you're going to need up front and find out how few of them you can use
make a hierarchy of which things are sub-groups of which things, and build out a structure
This isn't really a code problem. It's a design problem.
Without the design first, you can code a solution that gets like 80% of the way there
but you won't be able to find a fully realizable solution without knowing the full picture of what you need
I already did that but there are edge cases
Then you make events for those edge cases
yeah thats what I'm trying to do
If you have one effect that needs to be notified when a player lands on a platform, you make an OnPlatformLand event and give it to all of them
90% of the effects just go "Wow. This is worthless." and go about their day
but if you need it to happen, you make that event
can you describe this special case?
oh actually it might work
When I put references to a Singleton GameManager script in Awake, I get a nullreferenceexception error but when I put it in Start(), it works fine. Anyone know why that would be?
What line is giving you the error
HipFirePosition = GlobalReferences.Instance.HipFirePosition;
So GlobalReferences.Instance is null when that line runs
Is it because the Awake() is running before the GlobalReferences is initialized?
it is
if your singleton is set up in Awake then it is not guaranteed that one object's Awake method is run before another's. So what is happening is that object you are referencing the singleton in Awake is running its Awake method before the singleton's Awake method is run so the singleton has not been set up yet.
It is best practice to not access other objects until Start and to only set up an object's own state in Awake
I have one effect that changes which kind of bullet the character can shoot, my current idea is to have a class like this
public class CounterShockEffect : Effect
{
public event Action OnCounterShockOn;
public event Action OnCounterShockOff;
public override void ApplyEffect()
{
OnCounterShockOn.Invoke();
}
public override void UndoEffect()
{
OnCounterShockOff.Invoke();
}
}``` and then have the effect controller call ApplyEffect() on it to invoke the event. The effect controller would listen to this event and invoke its own event that is listened to by the weapon controller where all the bullet related stuff takes place
Thanks!
sounds like a shoddy design
Ideally an effect can be added to a player and removed in the same way and the effect itself is able to set itself up
e.g. player has functions or things that allow modification of the bullet shot and the effect itself can replace or change this itself
rn it seems like you have this Effect abstraction but are not using it well
btw its good practice to check null incase there are no listeners it doesn't throw null when invoked..
if(OnCounterShockOn != null) OnCounterShockOn.Invoke();
or just
OnCounterShockOn?.Invoke();
I mean the events are defined right there
how would they be null
by being invoked without listeners
Defined does not mean assigned
If an event has no listeners, it's null
ah ok
I feel like this is backwards. The effects should subscribe to events in the game, not the other way around. Your events should be told things like "Hey a player just landed a hit, do you have anything to say about that?" and then the effect could go "Actually I'm an invulnerability potion, please modify that damage to 0"
since i'm missing platform symbols for preprocessor directives - if i add, for example, UNITY_IOS here, would it work regularly
but why
they arent missing
its not defined if you are not CURRENTLY on the ios platform in the project
e.g. swap to ios, UNITY_ANDROID is no longer defined
oh my god is that so
true
I think in editor they exist if you have the platform installed however
but in builds the relevent platform defines exist for that plat only
I forget tbh
can anyone recommend me good unity asset to create car (free)
You have the same search bar we do. Search for "Car" and filter on free
so wait can i actually write UNITY_IOS even if it's undefined and it'll build for ios platforms
Oh My God
that won't magically make it build for iOS, it will just define that symbol so that preprocessor directives consider it true
the point of these is to have certain parts of a .cs file be included in compilation for certain platforms only
e.g.
#if DEBUG
Debug.Log("cool debugging shit");
#endif
no i get that
just deadass thought i was missing a way to check if the platform was IOS
there is Application.platform as a runtime alt
who knew unity only shows them when you switched build profile / module
its not shows but they are not defined when not needed so your ide doesnt show them
i know i just really didn't want to add to the runtime without needing to
so yea you can use UNITY_IOS just fine happy days
tysm
I have this small issue where my ball doesn't roll anymore any ideas why?
https://pastebin.com/yEEj4wDD
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
have you checked the constraints on the rb ??
The constraints are untouched nothing is checked.
nevermind I fixed it! had the gravity as !isgrounded
alright, so i've fixed my issue with shooting coins causing infinite recursion and that part's working mostly fine now. my current issue is that because i have two colliders, one larger one to act as the hitbox for projectiles to bounce and a smaller one on the parent object for the coin's physics, the coin is now being destroyed when the larger collider touches the ground; sometimes i can't even throw it without it being immediately destroyed. is there a way to prevent this? i'm a little confused
if anyone needs elaboration i'm happy to oblige
What am I doing wrong here? I can't move and my active gravity goes down despite character being grounded
private void GetMovement(Transform transform)
{
Vector3 vector = transform.forward * MovementInput.y + transform.right * MovementInput.x;
m_MovementDirection.x = vector.x;
m_MovementDirection.z = vector.z;
if (MovementDirection.x > 1f)
m_MovementDirection.x = 1f;
if (MovementDirection.x < -1f)
m_MovementDirection.x = -1f;
if (MovementDirection.z > 1f)
m_MovementDirection.z = 1f;
if (MovementDirection.z < -1f)
m_MovementDirection.z = -1f;
if (m_CharacterController.isGrounded && m_ActiveGravity <= 0f)
{
m_ActiveGravity = 0f;
m_MovementDirection.y = -0.27f;
}
else
{
m_ActiveGravity -= m_Gravity;
m_MovementDirection.y = m_ActiveGravity;
}
m_MovementDirection = m_MovementDirection.normalized * CurrentSpeed;
CollisionFlags collisionFlags = m_CharacterController.Move(MovementDirection);
}
oh nvm I know the issues
just FYI, that chain of if statements comparing the X and Z axes against 1,-1 is definitely not how you clamp your input. just use Vector3.Clamp01 or normalize it if you don't need to support speeds less than 1. what you are doing is still going to end up with diagonal movement that is faster than forward/back and strafing
ah okay, thanks
oh wait, I was misremembering the Vector3 method to use, I got it mixed up with Mathf.Clamp01, for a Vector3 you would use ClampMagnitude
Also there is no Vector3.Clamp01, only ClampMagnitude
Yeah
so for the max length I would just do 1f
what about for the negative clamp?
it's clamping the magnitude, magnitude is never negative
One problem, when stopping movement, my character still slides like 1 inch
It feels more like sliding than walking
show how you are actually applying movement
okay
private void GetMovement(Transform transform)
{
Vector3 vector = transform.forward * MovementInput.y + transform.right * MovementInput.x;
m_MovementDirection.x = vector.x;
m_MovementDirection.z = vector.z;
Vector3.ClampMagnitude(m_MovementDirection, 1f);
if (m_CharacterController.isGrounded && m_ActiveGravity <= 0f)
{
m_ActiveGravity = 0f;
m_MovementDirection.y = -0.27f;
}
else
{
m_ActiveGravity -= m_Gravity;
m_MovementDirection.y = m_ActiveGravity;
}
m_MovementDirection = m_MovementDirection.normalized * CurrentSpeed;
CollisionFlags collisionFlags = m_CharacterController.Move(MovementDirection);
if (collisionFlags == CollisionFlags.Above && m_ActiveGravity > 0f)
collisionFlags = m_CharacterController.Move(Vector3.up * -0.01f);
}
ah wait, it's at the bottom with the cc.Move call. so then it's likely how you are getting input
you're also normalizing after applying gravity which is wrong. and you don't need both the normalize and the clamp magnitude
your ClampMagnitude is doing nothing anyway since it returns the clamped vector
protected override void Awake()
{
base.Awake();
Debug.Log("Call FlyingEnemy.Awake()");
bushesCollider = GameObject.Find("BushesTilemap")
.GetComponent<TilemapCollider2D>();
Debug.Log("bushesCollider: " + bushesCollider);
flyingEnemyCollider = GetComponent<PolygonCollider2D>();
Physics2D.IgnoreCollision(bushesCollider, flyingEnemyCollider, true);
}
I want the dragonfries (which inherit this Awake() call; yes I checked, it is being called) to go through the bushes and all the bushes are on the BushesTilemap.
Do you guys have an idea why this is not allowing the dragonfries to go through the bushes? (dragonfries have PolygonCollider2D and BushesTilemap has a TilemapCollider2D)
Okay I changed it and it's still sliding a bit
ideally you would instead use something like layer based collision rather than manually calling IgnoreCollision
oh wait, before gravity
and again, this is likely due to how you are getting input. consider sharing that
that other info was just stuff that was wrong, not what was causing the sliding
I've been told that it was poor practice to have many layers
The alternative (easy) would be to create a flying enemy layer so that I would uncheck the collisions between flyingEnemies and bushes
this is still not showing the source of the input
note that the source of your input is in those MoveXRaw and MoveYRaw methods, not here, this is just where you are calling those methods
you also seem to be normalizing your input here, so why are you doing so again in the other method that uses the input to move the CC?
So do we have any ideas about how to proceed ignoring the collisions manually ?
Here is MyScript I was wondering how I can change the gravity of the player when jumping / falling. Right now it looks horrible the player doesn't get enough time in the air and feels to fast. I want a bit more time in the air. any ideas?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
should I make separate variables and just do if the rb.velocity > 0.01f?
can you either have the courtesy of selecting the correct language so there's syntax highlighting when using pastebin, or use one of the recommended code sites from #🌱┃start-here (also in the bot command)
ohhhhhhhhhhhhhhhh
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
bro you can see it
it's literally cropped
public static class PlayerInput
{
public static float MoveX() => GetInput(GamepadControl.GetAxis(InputControlType.LeftStickX), Input.GetAxis("Horizontal"));
public static float MoveY() => GetInput(GamepadControl.GetAxis(InputControlType.LeftStickY), Input.GetAxis("Vertical"));
public static float MoveXRaw() => GetInput(GamepadControl.GetAxisRaw(InputControlType.LeftStickX), Input.GetAxisRaw("Horizontal"));
public static float MoveYRaw() => GetInput(GamepadControl.GetAxisRaw(InputControlType.LeftStickY), Input.GetAxisRaw("Vertical"));
public static float LookX() => GetInput(GamepadControl.GetAxis(InputControlType.RightStickX), Input.GetAxis("Mouse X"));
public static float LookY() => GetInput(GamepadControl.GetAxis(InputControlType.RightStickY), Input.GetAxis("Mouse Y"));
public static float LookXRaw() => GetInput(GamepadControl.GetAxisRaw(InputControlType.RightStickX), Input.GetAxisRaw("Mouse X"));
public static float LookYRaw() => GetInput(GamepadControl.GetAxisRaw(InputControlType.RightStickY), Input.GetAxisRaw("Mouse Y"));
public static bool Run() => GetInput(GamepadControl.GetButton(InputControlType.LeftStickButton), Input.GetKey(KeyCode.LeftShift));
public static bool Jump() => GetInput(GamepadControl.GetButtonDown(InputControlType.Action1), Input.GetKeyDown(KeyCode.Space));
public static bool Crouch() => GetInput(GamepadControl.GetButton(InputControlType.RightStickButton), Input.GetKey(KeyCode.LeftControl));
public static bool Interact() => GetInput(GamepadControl.GetButtonDown(InputControlType.Action3), Input.GetKeyDown(KeyCode.E));
public static bool Attack() => GetInput(GamepadControl.GetButtonDown(InputControlType.Action2), Input.GetMouseButtonDown(0));
public static bool Pause() => GetInput(GamepadControl.GetButtonDown(InputControlType.Pause), Input.GetKeyDown(KeyCode.Escape));
}
private static T GetInput<T>(T inputGamepad, T inputKeyboard)
{
if (!inputGamepad.Equals(default(T)))
return inputGamepad;
if (!inputKeyboard.Equals(default(T)))
return inputKeyboard;
return default(T);
}
There a way to paste the code like this ?
that was not directed to you, it was directed at the person who used pastebin. but you can see code sharing guidelines here: #💻┃code-beginner message
yes, in a code block
there we go
oh like
protected override void Awake()
{
base.Awake();
Debug.Log("Call FlyingEnemy.Awake()");
bushesCollider = GameObject.Find("BushesTilemap")
.GetComponent<TilemapCollider2D>();
Debug.Log("bushesCollider: " + bushesCollider);
flyingEnemyCollider = GetComponent<PolygonCollider2D>();
Debug.Log("flyingEnemyCollider: " + flyingEnemyCollider);
Physics2D.IgnoreCollision(bushesCollider, flyingEnemyCollider, true);
}
That's nice
i didn't know about cs after the backticks
quick tip for strings, you can write the them as
// this
Debug.Log("bushesCollider: " + bushesCollider);
// is the same as this
Debug.Log($"bushesCollider: {bushesCollider}");```
Oh actually I solved my pb, I had to ignore the CompositeCollider2D, not the TilemapCollider2D
Im kind of confused, I used to be able to see GameObject stuff in the inspector, but now its just simply not showing anymore?
If you mean the Camera_Move script at the bottom, remove it and (try to) add it again
wait, it was because I had a compliation error
sorry
I guess while Im here, the editor is saying it doesn't recongize "Room" even though I establish it above?
public class FallScript : MonoBehaviour
{
public GameObject Player;
public GameObject Camera;
public GameObject CameraTrigger;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
GameObject Room = CameraTrigger.GetComponent<GameObject>();
}
void OnTriggerEnter2D(Collider2D collider)
{
print("worked2");
Player.transform.position = new Vector2(0f, 0f);
Camera.transform.position = new Vector3(0f, 0f, -10f);
Room = 1;
}
}```
Room Established in the first place
using UnityEngine;
public class Camera_Move : MonoBehaviour
{
public GameObject Player;
public GameObject Camera;
public float Room = 1;
void OnTriggerEnter2D(Collider2D collider)
{
switch (Room)
{
case 1:
Camera.transform.position = new Vector3(18f, 0f, -10f);
Room = 2;
break;
case 2:
Camera.transform.position = new Vector3(0f, 0f, -10f);
Room = 1;
break;
}
}
}```
You have created a local variable Room inside of Start.
Local variables cease to exist when the function they're declared in ends
tysm
Not only is it a local variable but you declared it as a GameObject, so you can't set Room = 1
(don't get confused with your other script which is completely irrelevant.)
I was working off of HingeJoint hinge = GetComponent<HingeJoint>(); from the unity website, tried to get a Component
ok, but GameObject isn't a Component, so it just doesn't make sense at all there
I seen it in Properties of the Component page
also, minor note (deal with this later) - you usually won't need serialized variables of type GameObject. use the type that you're actually working on, like Transform for Camera/Player, or... whatever you're trying to get from CameraTrigger
that does not mean it's a component
a component extends Component, not that it's inside Component
I guess so
colliders have a rigidbody property, but rigidbodies aren't colliders either
is there a list of Compoents out there to find one that would help me here?
you need to step back from the code and figure out what it is exactly that you're trying to do
Im trying to call on "Room" from the other script, to set it back to 1 when the Trigger event is done
you get a component you already know. if you were adding a component, that's when you'd be looking for existing ones
when you're at GetComponent, a list of available components in the engine isn't going to help
so what's the other script called?
you would use that
(preferably, you would use that as the type of the variable to begin with)
The other script is CameraTrigger
then you would use that type
So you'd use that
make sure not to confuse the type vs the name of a variable
Choose the best way to reference other variables.
so would it be this? GameObject Room = CameraTrigger.GetComponent<CameraTrigger>();
GetComponent returns the type you give it in <>
You cannot store a value of type CameraTrigger in a variable of type GameObject
is anyone able to help me with this? i can send a video if i need to
CameraTrigger has a room, it isn't the room itself
sounds like you're really confusing "is" vs "has" relations here (indicated by the "components have gameobjects" thing before)
honestly the entire line of code is stumping me
i mean, you don't need it to begin with
you can just have the variable named CameraTrigger be typed as a CameraTrigger
Green is a GameObject.
Red are components.
like, my next question would be if this was correct*
CameraTrigger Room = CameraTrigger.GetComponent<GameObject>();
definitely not
GameObject is not a component
ok, stop what you're doing
you're just stumbling randomly now
that won't be productive
go actually learn the relevant concepts here
have you done the unity essentials pathway?
GetComponent does exactly what it says it does. It gets a component. You tell it which kind of component you want to get.
Then you can put that in a variable
that can hold that kind of component
I tried the Unity Essentials Pathway and it broke
elaborate
I looked at the documentation, thats why Im here, because I looked at the documentation and tried to figure out but now Im here. I didn't thoroughly look through the huh how page, but it was confusing me so I looked at the documentation
also one moment on the elaboration*
So, look at this line you referenced before. You see how the variable is of type HingeJoint. And the GetComponent has HingeJoint as a parameter
when I did the in engine essentials pathway (I scimmed most of what I already understood) when I got to the part with scripting, (I got several errors about the prewritten code that made the player character fly. the tutorial not telling me to make the player a rigidbody, and what type of rigidbody as well)