#💻┃code-beginner
1 messages · Page 373 of 1
Well, the main difference is value vs reference type. Everything else stems from that.
You could use methods in primitive types, like int, too.
Methods are not a defining feature of classes.
https://hatebin.com/fvwnrpkwvl I am following a tutorial which I talked a bit about yesterday. I have this script but it says cannot resolve symbol properties. I could not find a fix for this
Share the whole error with it's details
It says the type or namespace name 'Properties' does not exist in the namespace 'Unity'(are you missing an assembly reference?)
Did you install the Properties package?
no because I could not find it in the package manager
the whole error with it's details the next time. We don't want to guess what line it is.
All right. Sorry.
You can't just skip the package installation if you can't find it. You can't use the package if it isn't installed
I see. I have to install the package all right. I cannot find it though. I'm just searching for properties but maybe its named something other?
Not all packages will show up in the PM, some need to be added manually by name. I've never heard of the properties package, so can't say if this is the case
There's usually install instructions on the docs
Does the tutorial not cover the setup steps?
Share a link
I am just getting the files from the repository now. There are things different from the video tutorial and the repo files. So I thought I would just get the repo files since they'd be the most updated ones.
and no not step by step
Packages are usually omitted from repositories
They should at least mention what dependencies you need and where to get them.
ohh okay. Thanks did not know that. I thought everything would be in there.
There's also the matter version. Make sure you're using the same unity version as the tutorial
Ah so it may be built in in the newer versions? Makes sense. Thanks for the help.
Or removed in an newer version. Apis change over time.
from the docs, looks like it hasn't been updated in quite some time - and was still in the experimental stage (so won't show up in the list of packages)
What am I not seeing here?
public interface IAssetRepository<out T>
{
IEnumerable<T> GetAll();
protected string ResourcePath(); // <-------
}
public class StorableItemRepository : IAssetRepository<ItemSO>
{
public IEnumerable<ItemSO> GetAll() => Resources.LoadAll<ItemSO>(ResourcePath());
protected string ResourcePath() => "Items/Storable"; // <------ PROTECTED NOT ALLOWED
}
make the interface implementation of ResourcePath sealed
Virtual
The base class property needs to be virtual
sorry, not what I meant, sealed in the Interface declaration, not the implementation
The question was why I was not allowed to inherit protected interface methods, and how to do it instead :p
public interface IController
{
virtual void DoIt() { }
}
class Test : IController
{
protected void DoIt()
{
throw new NotImplementedException();
}
}
If a method is not abstract it must have a body
So in your case either make it abstract, or return string.Empty if that works
Why do you want to seal the property anyway? If it's not virtual it can't be overridden, so it's sealed
Mm, let's go a step back. Because maybe that's not what I really want?
What I want is to have a interface that requires its implementors to define a string without making that field public
And at compile time
You can specify internal features that must be implemented with an interface, but that's about it
What you want does not fall under the purpose of an interface
Abstract classes have more control since they allow protected, but this is obviously different over interfaces
Hey, I have a simple script with the ExecuteInEditMode attribute. Its Update method is called on runtime. Am I missing something?
[ExecuteInEditMode]
public class Test : MonoBehaviour
{
private void Update() => print("Test - Update");
}
Oh, yeah
By adding this attribute, any instance of the MonoBehaviour will have its callback functions executed while the Editor is in Edit Mode **too**
https://docs.unity3d.com/ScriptReference/ExecuteInEditMode.html
Yeah, I completely missed that
For some reason, from the past experience using it, I thought it disables it on runtime
I think the past experience hasn't brought me much then
hey guys.
how can i convert WeaponConfig<Firearm> to WeaponConfig<Weapon> to get its public properties?
Firearm inherits Weapon, and WeaponConfig is a scriptable object :
What are the properties you need?
In a normal polymorphic design you shouldn't need to do that
i have idffrent scripts like my weapon manager and UI manager, that need to access the icon Sprite, the dropped prefab, the player prefab, and the weapon type enum.
the weapon class is an abstract monobehavior with a Configuration property.
i am trying to override its getter in the Firearm script so that it returns config_ which is of type WeaponConfig<Firearm>
Shouldn't those fields be on all WeaponConfigs
So then why do you need the specific subclass
This seems overcomplicated TBH
Making a non-generic parent class might serve you well
Why does fire mode need to be generic
idk how to explain it. can we just skip that find another work around?
sorry xd
i guess i can send over all of my scripts so you can make of it what you will but i dont think anybody has the time or patience to read all of my code
Firearm might inherit from Weapon, but WeaponConfig<Firearm> and WeaponConfig<Weapon> don't have that relationship. They're 2 unrelated classes.
So, Unless you implement a custom convert method, there's not much you can do
any way for me to get these public properties from any class that inherits from Weapon?
My recommendation is to redesign this with less polymorphism, more composition.
You can cast the Weapon into the specific inheriting class, but that's a meh solution
If the properties are part of Weapon, that's all you need
If they're common to all weapons they should be part of Weapon
nothey are just in the weapon config
Weapon should have a non generic WeaponConfig
Or at least a way to access it that way
but i dont get it.... all WeaponConfig instances, no matter the type, should have these properties i mentioned. so why is it that i cant just get them?
Because you haven't exposed it as a non generic version of WeaponConfig on Weapon
You don't have the ability to do that because you didn't make a non generic parent class for WeaponConfig
i guess i can do this, but it doesn't seem like a proper solution.
how do i do that?
WeaponConfig is a scriptable object btw
Make a class that doesn't have generic type parameters as the parent class
Of WeaponConfig
With all the fields on it except the parts that need to be generic
It's unclear what those are
what would the declaration of these two classes look like? if you dont mind me asking
the parent class and WeaponConfig
public class WeaponConfigBase : ScriptableObject
{
//your properties
}
public class WeaponConfig<Firearm>: WeaponConfigBase
{}
If you really need generics
I rarely ever have a need in them
@vast vessel
all of my fire modes, need the ReloadCoroutine, UseCoroutine, and StopUse coroutines.(which are called when the according buttons are pressed)
but heres the thing, i am going to be implementing different fire modes, for specific weapons, and they to get specific properties, from those weapons.
for example, my Firearm_Firemode class, needs to get specific properties, from Firearm, which don't exist in Weapon,
like firearm.isReloading, or firearm.raycastOrigin, and firearm.loadedAmmo.
this is why i made the Firemode class generic. so the methods are also generic and now, all classes inhareting from Firemode, can be used on any kind of weapon.
Feels super convoluted to me.
I also don't understand how Firemode needing to be generic is related to your previous question.
maybe i should leave this till tomorrow, this bricked my brain.
idk wtf im doing anymore
The relationship between all these classes is unclear.
What is a Firemode? Is it a mode of firing that a character has? Is it specific to each weapon?
So equipping a different weapon changes the way it is fired?
Why cacn't it be implemented in the weapon then?
Why might access token here always be null?
public async Task InitSignIn()
{
await UnityServices.InitializeAsync();
await AuthenticationService.Instance.SignInAnonymouslyAsync();
var playerInfo = await AuthenticationService.Instance.GetPlayerInfoAsync();
var linkedAccount = playerInfo.Identities;
if(!linkedAccount.Any(u => u.TypeId == "unity"))
{
SignInButton.SetActive(true);
}
Debug.Log("Init Sign In is successful.");
var accessToken = PlayerAccountService.Instance.AccessToken;
Debug.Log("Access Token: " + accessToken);
}
Sounds like it would be related to PlayerAccountService code. Presumably it's not being assigned.
How would I assign it?
We don't have nearly enough context here to answer that
here is what im trying to implement:
i have a weapon manager class that needs to have a list of weapons, that i can assign in the inspector,
it also needs to be able to call these functions, on any of these weapons : ReloadInputStarted, SecondaryAttackInputStarted, PrimaryAttackInputStarted and PrimaryAttackInputCanceled
now, i need each weapon, to have several ways of using that weapon, eg:
a rifle needs a semi auto, and an auto mode
a grenade needs a throw, and a drop mode,
a smg, can both shoot normal rounds, and it can also use its under barrel grenade launcher.
i call these firemodes. so the smg i mentioned, needs two fire modes, one for shooting rounds, and one for shooting grenades.
the weapon that has these firemodes, calls a function from its active firemode, and then the fire mode does what its supposed to do, like shoot bullets, instantiate a grenade prefab, or just Log something in the console. the behavior of each firemode will be defined in itsown class and all firemodes need to inharet from one class, so that one weapon could do multiple things.
some fire modes also need to store their ammo on their weapons script. which is why my firearm script, has this :public Dictionary<AmmoType, float> loadedAmmo;
this is where any firemodes that take ammo, store their ammo data.
phew
Im trying to setup controller support for my game, and i followed a brackeys tutorial. This is pretty much identical to that code aside from variable names, but it doesnt register the inputs. Any ideas why?
Am i missunderstandig?
You haven't enabled the input actions.
I don't see why that would require anything to be generic.
WeaponManager => list of Weapons
Weapon => list of FireModes
Weapons setup their specific firemodes from their settings/configs and call the required methods on them. If a fire mode needs to consume ammo, it can either call a method on a weapon with the required ammo type and amount, and the weapon would handle the dictionary, or the weapon could subscribe to a Fired event in FireMode to adjust it's ammo. You could also pass the ammo dictionary to the fire mode during setup and it would do it's own thing without needing to access the weapon at all.
So many ways without using generics, that imho make things way more complicated than they should be.
You can do that with something like Controlls.Gameplay.Enable();
Ah ok cool thanks
i thought i was missing something
Also, I'd just do this in Update instead:
tbh i would just do this in Update instead:
move = Controlls.Gameplay.LJoystick.ReadValue<Vector2>();
I do this for continuous values.
subscribing to performed makes sense for "button" style inputs
and one other thing: "LJoystick" isn't a good action name.
Actions are supposed to be things you do in the game.
like "move" or "shoot"
You bind things like "left joystick" or "X button" to those actions
The Three Commandments of OnCollisionEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt not tick
isTriggeron either - Thou Shalt have a 3D Rigidbody on at least one of them
hi ive been going through unity.learn and its just so confusing what do i do
- Though Shalt not be using 2d game with 3d collision detection.
First you explain what your problem is.
so im on early stages of the unity.learn havvent even touched scripts and its all already too much for me
How do I ensure an access token is created? I'm just logging in anonymously and then linking to Unity Player Accounts, but I never can return an access token after logging in anonymously.
Do you know how to program at all ?
no
Step 1: Go to youtube and learn programming fundamentals
show us what pathway you are following
wdym?
you said you are using unity learn
yeah i just clicked a link and started idk what im doing
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hey guys I'm currently taking unity's junior coding class and I'm kinda stuck on when to use rotations and or spacing between the code and adding other information in between. (sorry if I'm not making sense, I'll put a piece of the code below this)
i think im on essentials
Are you talking about when you should pick between these two things?
foo.Bar(one + two + three);
Vector3 combined = one + two + three;
foo.Bar(combined);
its when I use new Vector3 and ending the line with transform.rotation
is there a way i can convert that joystick input into a float? i want to rotate my object on the Z axis around (0, 0) to make it face the same direction as the joystick is, but to do that i need the float to set the Z as instead of the Vector 2
Consider using Vector2.SignedAngle
It gives you the (signed!) angle between two vectors
Vector2.SignedAngle(joystickInput, Vector2.right);
this gives you an angle between -180 and 180
You can then use this angle to calculate a rotation.
Quaternion.AngleAxis(angle, Vector3.forward);
assign that to transform.rotation and the object will rotate
@swift crag im doing essentials
I might have something backwards here, so you may need to do -angle instead of angle.
private IEnumerator TriggerEnd(float delay)
{
OnMinigameEnd?.Invoke();
IsPlaying = false;
yield return new WaitForSecondsRealtime(delay);
minigameCameraMover.MoveToPlayer();
Stop();
Debug.Log(1);
Debug.Log(inputRestoreDelay);
yield return new WaitForSecondsRealtime(inputRestoreDelay);
Debug.Log(2);
Player.interactionSystem.CanPerformInteraction(true);
if (endExtensions) endExtensions.PerformActions();
}
Why is the 2 not printing, but 1 and inputRestoreDelay is printing? The inputRestoreDelay is 0.1s. I'm not disabling the gameobject, not disabling the component and not destroying the gameobject, and not stopping the coroutine anywhere. Time.timeScale is 1
The second line is calculating a Vector3 out of a few different values.
It's a long enough expression that it's worth putting on its own line.
You could just shove that entire expression into the last line
How are you starting the coroutine?
so can i have help or atleast some advice?
public virtual void MinigameEnd()
{
StartCoroutine(TriggerEnd(endDelay));
}
it's printing 1 and inputRestoreDelay
becase thats what i was already doing and its too much what do i do
if this is on a different game object, perhaps you're deactivating that object
how do i solve this then?(simplified version of my system)
Can you take a screenshot of the console?
it's the same gameObject
sure
ah, yeah, it's this.StartCoroutine(this.TriggerEnd(delay))
Pass the message when setting up the firemode.
i can't really tell you much if all you've said is "I don't understand any of it"
@teal viper
this is an example.
i need to pass things like refrances to transforms and visual effects and light components
myFiremode.Setup(configs, message);
i mean its overwhelming with how many different windoiws i have to pop up and there was somthing about a license erlier idk
i tried restarting unity but it didin't help
even if i put yield return new WaitForSecondsRealtime(0);
it doesn't execute anything below that
yes, game development involves using your computer...
Btw, this should work as is anyway. What's the problem with it?
dosent really explain much
firemodes are scriptable objects. which is why they need to get this info, from whatever weapon calls their use method
does the behavior change if you remove that Stop() call?
Can you put the whole !code somewhere, because the Stop command is sus, MiniGameEnd.Invoke is sus.
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I don't see how that's related.🤔
yeah
it's pretty big class tho
Even if they're SOs, they can be provided info from the weapon.
I'm a pretty fast reader tho
we'll survive
many weapons will be using the Use function of the same SO
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.
248 line
Then perhaps the use of an SO is not a great idea here.
so are you going to explain it?
I literally can't tell you anything. All you've said is "I'm confused by everything".
the scriptable object should tell the weapon how to work. you shouldn't be mutating data inside of the scriptable object
What is OnMinigameEnd?.Invoke(); What does that do?
You could use the SO to construct a runtime time object representing the firemode. That you can configure from your weapon and pass in any info you might need.
so what should i do then?
Each fire mode SO holds the configs related to it. here is an example for a firemode, used by all kinds of guns:
restoring input, disabling minigame UI
i explained that there was a licence thing i had to do and idk what that was and im asking how long it would take to get used to it bc there is way too much for me to handle
nothing else
thats what im saying. i dont want to change data inside of the SO
that's not a firemode! that's the entire damn weapon!
figured it out, i had a StopAllCoroutines() on class that interhited from Minigame
it holds all of the behavior related to it.
thats just what i call them, but in my case, a fire mode can also be for a sword or a grenade as well.
fixed! 😄
This sounds like FireModeConfigs rather than FireMode.
I would punt the runtime logic into a separate class
The weapon definition tells the weapon what kinds of things it should do
The weapon actually does them
So it was the Stop command...
i need each weapon, to have several ways of using that weapon, eg:
a rifle needs a semi auto, and an auto mode
a grenade needs a throw, and a drop mode,
a smg, can both shoot normal rounds, and it can also use its under barrel grenade launcher.
each of these is a firemode
in your SO, you could have something like:
public FireMode CreateFiremode()
{
return new SpecificFireMode(initialConfig);
}
Then in the Weapon you'll provide it any additional data it might need.
so you want me to have an instance of each fire mode on each of my weapons?
that sounds a bit wasteful on the memory side of things
plus, all weapons that have shared firemodes, will work the same. cant the firemode config process the data?
why make an instance for each weapon
Only a little bit. But it's a lot better than letting your SO execute runtime logic.
if there are 20 npcs, using a rifle that has 3 firemodes, thats 120 instances
instead of just 3 firemode SOs
Because you apparently need it to hold some state
Or what do you need it to access on the weapon?
What did i do wrong i cant seem to find out?
But then you'll have a lot of instances of generic classes, which doesn't really fix anything
And probably makes it a bit worse too
You can keep the SOs approach if they don't need any specific state.
If the implementation of the SO is the same for all the weapon types, there shouldn't be any problem
what im saying we should do is this : for a normal gun firemode, all of the data(audio clips, damage, force and etc) stored on the SO.
then, have a Use method on the SO, which takes a muzzle transform from the weapon calling it, and then process the shooting using the data on the SO.
its not
melee weapons, projectile weapons, raycast weapons and etc will need their own behavior
and i want each weapon to have multiple behaviors
like a gun that has both a raycast mode, and a projectile mode
maybe two raycast modes with diffrant fire rates
you get the idea
have you played half life 2?
Well, in this case, I'd have a separation between the SO that holds the mutable config only and the runtime logic, that operates on the specific variables.
sure
do you remember this gun that could shoot bullets, and launch energy barlls as its seconday attack?
im saying is, each of those could be a firemode, and then the weapon script, would call the Use function of each of those fire modes, depending on wich mouse button is pressed
Yes. I got the idea of what you're trying to implement, quite a while back. There's no need to clarify it.
setting properties in scriptable objects from code just seems like a sin
idk
Yes, and that's what the plain classes with their own logic would do. The SOs would just hold immutable data and generate these fire modes.
Definitly. I don't recommend that either.
ohhh. so like a Weapon script, a Projectile Launcher script and a Raycaster script on the same weapon, where the Weapon scripts calls a Use function on one of the two other scripts?
and the Projectile Launcher script and Raycaster would have SO fields for their config
right?
because that sounds way better then... whatever the fuck this is...
No. Your specific Weapon script would hold a list of FireModeConfig SOs. Then when it's initialized, it would call firemodeA = firemodeConfigA.GetRuntimeFireMode(thisWeaponConfig) for each SO and store the returned firemodes in a list or something. Then just use these firemodes as you described.
making a tutorial system for my game and i have a set of keycodes i want the code to listen for, how do i specify this?
i want to keep this as modular as possible
a loop that checks all the keys in the array
That's just a scriptable object of t weapons where t weapon would be constrained to weapon.
and how would i set that up
Wrap it in a for loop
Yea ik.... i wrote that.
Long story short i didn't end up working out
What was the original question?
Ty 👍
Hey guys, how do I make my player take continuous damage while coliding wiht an enemy?
Maybe consider using on collision stay (as well)?
alright ima look into that
Set some bool to true. Check it in update and if it is true, apply damage. Set it to false on exit.
Are Fire Arms and weapons related?
aite
yo this works but now my player dies too fast HAHA
Firearm inherits from Weapon
ill just lower enemy damage
now how do i despawn an enemy?
nvm foundout
wiat now my enemies arent spawning anymore after 1 dies
😭
Well, the SOs are completely different types like a List<int> isn't the same as a List<float> so you'd need to create a new SO instance and extract/cast all the data from the source to the target. Sounds convoluted and you'd probably be better off decoupling some data.
Don't put the spawn script on the enemy
That is my guess on what is happening
Has the spawn script been provided yet?
sry i dont understand what that means
is this what u guys mean?
Yeah. For 1, that "enemy1" should be a prefab, not an object in the scene
What object is that attached to?
And dalphat is asking to see the actual code
You are spawning newEnemy
enemyPrefab is what should be in every instantiate call
Don't even pass a gameobject into the coroutine, just use enemyPrefab
Maybe just have a loop instead of Starting new coroutines after spawning?
while(true)
{
yield ...
Instantiate(...)
}```
Why? What exactly are you trying to do with sleep?
oh wait is that the yield line
aite
mb if its frustrating, i just started tdy and just yoloed a project without watching any guides ;-;
Minor stuff but for optimization purposes, consider caching the new yield instruction before the loop and just yielding that cache in the loopcs var wait = new WaitFor... while(true) { yield return wait; Instantiate(...); }
aite, ima add that in
whats this error?
It's saying that you cannot have that statement outside of the method
You can't use var outside of a method.
you need to use the actual type
In the coroutine before you'd delay/instantiate - before the while loop
Also - yes if you want it to refernece another field, the initialization needs to go in a method
like this?
ahh i see
yep ran it and it works
yoooo it works, tysm guys
i wanna revisit this tho what does this mean? my enemy currently is just chilling offscreen waiting to be cloned
Yeah, use a prefab, not anything in the scene
Prefabs are blue objects from the "project" window
I do recommend you at least go through the essentials pathway here
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Prefabs are created automatically when an object is dragged from the Hierarchy into the Project window.
https://learn.unity.com/tutorial/prefabs-e#
alright ill take a look at those links, thanks
how do I do a ground check in 2d?
like this so i can just delete my boi on the screen?
does anyone know how to stop this from happening?
the box im talking about
whats that
on your keyboard, "ins" . . .
at least, for an american keyboard . . .
okay it fixed it thank you 🙏
is there a function for dontdestroyonloadobjects that activate when a scene is changed
tried this and it doesnt work
what is this trying to do?
you need to actually define OnSceneLoaded
did you create a method called OnSceneLoaded?
basically i want to spawn a gameobject every time the scene is changed
What is OnSceneLoaded
Unity project won't start anymore. I discarded all changes in Github back to the last working version and it still won't start. Nothing in the console. How do I troubleshoot this?
so the project opens, but you can't enter play mode, you mean?
I can press play but it's just a blue screen
you have the wrong scene open, probably
Then presumably your scene is just a blue screen
Oh you're right
Fuck
Why did it decide to do that? It's never done that in the dozens of other times I've run it 🤦♀️
Just wasted all that work, time to kms
Opening a scene is "all that work"?
they threw out changes from git
Ah
Using github desktop, it stashes all or none 😕
Used to VS where you can pick and choose the files
Sucks
You should probably just use the command line. Desktop clients are all different but git CLI is git CLI wherever you go
yo after i made it a prefab im running into this issue
(this is a situation where stashing everything makes sense, of course)
i didnt touch the script at all
What is line 29
you didn't have to touch the script to cause an error
Yeah I'm reluctant. It's one of those things, it's nowhere near as scary as it looks like regex
You need to drag the prefab into the enemyPrefab field
Then there exists an instance of EnemyStats where player is not set
Oh huh. Different wrror?
wdym by this?
and how do i go about fixing it?
I mean exactly what I said. There exists an instance of EnemyStats where player is not set
consider examining the enemy1 prefab
its this
then what do i do about it?
that's not a prefab that's a script
Do you not know what a prefab is?
barely
Find the instance of EnemyStats that has no player set and set player on it
type mismatch? does my player have to be a prefab as well?
Prefabs cannot reference objects in the scene
"Type mismatch" will appear when you have an invalid reference.
oh ffs
Question: Why is this a public field anyway
my player is an obj on scene
why not just use the player you've collided with
no idea, is this bad practice in general?
Well, considering it literally does not work
if the enemy only cares about the player when they hit the player, you don't need to tell them about the player in advance
you just whacked into the player
I would say yes it's bad practice to use something that literally does not function
so wld changing it to private fix it
It's the fact it's not set properly
No, getting rid of it entirely and using the object you hit would fix it
changing it to private would simply guarantee that player is null
wdym by this?
im kinda lost sry
suppose you have a game with 100 enemies
Enemies should probably automatically find and store a reference to the player script.
would your bullet class look like this?
pubilc Enemy enemy1;
pubilc Enemy enemy2;
pubilc Enemy enemy3;
// ...
pubilc Enemy enemy100;
They mean that if the enemy only cares about the player when they hit the player, you don't need to reference the player in advance
use the object you hit
You're already checking its tag so you know how to reference it
Just, use that
why material.shader.renderQueue is 3000 in editor while being 2000 when checked with code
ngl i just copied code for that line
So now you can read it
and understand what it does
Break down the problem you're working on more finely. If you don't understand prefabs, don't proceed until you learn them.
man i wish i cld answer you but i really dont know
You're taking on too much at once. Take a step back and start simpler
yeah i think so too HAHA
If you've copied every line of code, then you will have no idea how to write your own code
Consider !learn .
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
you would not store a list of every possible enemy in the bullet
you'd just check if you hit an enemy, and if you did, you'd deal damage
Enemy enemyComponent = collider.GetComponent<Enemy>();
if (enemyComponent) {
enemyComponent.Hurt(10000);
}
perhaps
i understand what youre saying but idk how to apply that to my own code, sry
ill just take a step back and learn more first
before attempting this
thanks for all the help tho guys!
Look into coding with C# and unity fundamentals first. If you copy code without understanding it, you're building your foundation on unstable ground. You don't even understand your current position, even less so how to progress from it.
yeah lol, got a lil too excited when i downloaded unity
If you want to use Unity from the start, copy code one snippet at a time and do not continue until you understand the code.
Cannot tell you how many times I've made the mistake of just copying code
yep, rushed a little to much into it
wanted to try to make a game before I start working so i felt the pressure
Hi guys i'm making a prop hunt like game and i have groundCheck with Collider.bounds.extents.y but with some model my result don't return true someone know why ? or have a better method to do a groundcheck
My game lags so much on android and i dont know why
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField] private bool isPlayer1 = true;
[SerializeField] private bool isPlayer2 = true;
public Transform playerPosition;
[SerializeField] private GameObject bulletPrefab;
private float rotationStrength = 0.5f;
[SerializeField] private Bullet bulletScript;
void Start()
{
playerPosition = GetComponent<Transform>();
}
// Update is called once per frame
void Update()
{
if (isPlayer1 && Input.GetButton("Fire1"))
{
transform.eulerAngles = transform.eulerAngles + new Vector3(0,0, rotationStrength);
}
if(isPlayer1 && Input.GetButtonUp("Fire1"))
{
bulletScript.Shot();
}
if(isPlayer2 && Input.GetButton("Fire2"))
{
transform.eulerAngles += new Vector3(0,0,rotationStrength);
}
if (isPlayer2 && Input.GetButtonUp("Fire2"))
{
bulletScript.Shot();
}
}
}
this wont shot for some reason
Run the profiler
how? sorry im very new too unity
By opening it and hitting play. There are plenty of good guides online about the profiler. I recommend having it in hierarchy mode
If you need to profile the game on your phone, look at https://docs.unity3d.com/Manual/profiler-profiling-applications.html
Hello everyone, I am trying to make Inventory but it doesnt work, I want it that when I pickup an item it will go to the first empty slot and change icon according to item I picked up, I want it to be able to pickup other items while Im holding my item and that other items will be assign to remaining empty slots. And I want it to switch between them with numbers from 1-5 and when I press G on item Im holding it will drop it from hand and inventory. This is Item script thats attached to items:https://hastebin.com/share/ozagayorev.csharp and this is Inventory script attachted to gameobject holding 5 slots(which are 5 ui images): https://hastebin.com/share/uficaziniw.csharp and this is interaction manager script: https://hastebin.com/share/afabehexiq.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Show the inspector of this object.
the bullet?
Whatever has the code you just showed
ok
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class Bullet : MonoBehaviour
{
// Start is called before the first frame update
public float speed = 50f;
public Rigidbody2D rb;
[SerializeField] private Gun gunScript;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
}
public void Shot()
{
Instantiate(gameObject, gunScript.playerPosition.position, gunScript.playerPosition.rotation);
rb.velocity = Vector2.left * speed * Time.deltaTime;
Destroy(gameObject, 3f);
}
}
This isn't what I asked for
then what?
The inspector of this object
should I screen shot it?
yes
So, whatever object you have assigned to BulletScript should be cloning itself, then setting its own velocity and destroying itself. I wonder, why are you doing it this way? Your gun already has a reference to the prefab. Wouldn't it make more sense to instantiate that prefab rather than having your bullets clone themselves at some random point in space?
So I should make a method that instantiates the bullet within the gun script instead? I did this because I put a velocity (this was before) on the bullet before it got instantiated and it would go left instead of going in the direction it is facing.
So instantiate the bullet, then set its velocity
Ill try that, ty
Trying to make this effect in my game where text fades in when an item is grabbed and stuff, and if multiple items are picked up fastly it will show like this and so on
But if grabbed too fastly it appears like this?
When the first popup starts, it will always be at the same position, something around (0, 177). ANd it lerps to that position, THen while its on screen if another box is picked up, I am lerping the existing popup(s) upwards by 1, to leave room for the new popup to spawn at the same position (0,177). It works slowly but not wwhen pickedup fastly.
Instead of describing your code, show it. "Lerping the existing popups up by 1" and other stuff sounds very weird, plus you are describing what you think your code does. That might not be what it's actually doing
I am using a coroutine to lerp them. I assume the issue is: When a popup exists, and the player grabs a new box, the existing popup(s) will all move up to make room, but, whilst those popups are lerping up to make room, if the player grabs another box, the existing popup(s) should account again and their destination should be up more.
Its because i've named stuff weirdly and im not sure if its understandable
public void MoveUp(float amount)
{
//If just spawned in and another one spawns in, adjust endposition to go above that
if (isMovingUp)
endPosition += Vector2.up * amount;
//If already moving up due to another and another spawns, adjust out smooth up destination
smoothUpEndPosition = rectTransform.anchoredPosition + Vector2.up * amount;
if (isSmoothMoving)
{
StopCoroutine(smoothMoveCoroutine);
smoothUpEndPosition = new Vector2(smoothUpEndPosition.x, smoothUpEndPosition.y + amount);
}
smoothMoveCoroutine = StartCoroutine(SmoothMove(rectTransform.anchoredPosition));
}
private IEnumerator SmoothMove(Vector2 from)
{
float elapsedTime = 0f;
isSmoothMoving = true;
while (elapsedTime < moveUpDuration)
{
elapsedTime += Time.deltaTime;
rectTransform.anchoredPosition = Vector2.Lerp(from, smoothUpEndPosition, elapsedTime / moveUpDuration);
yield return null;
}
isSmoothMoving = false;
rectTransform.anchoredPosition = smoothUpEndPosition;
}```
This is on each popup, MoveUp is called everytime a new popup happens, so it can move up for the new popup. the IEnumerator SmoothMove() is so it can smoothly move upwards.
You should try free tools like Dottween
I have DOTween, i cant figure out how to do that here
my if (isSmoothMoving) is for, if we are already moving to adjust room for a new one,and this function gets called again (a new popup has spawned) we must adjust our destination
I feel kinda silly - can anyone remind me of the proper way to check for a spacebar press? Unity 2022.3.30f1
if (Input.GetKeyDown(KeyCode.Space) && (selectedDialogueType == DialogueType.Text || selectedDialogueType == DialogueType.Talk))
{
OnNextNode();
}
This isn't working - it does with mouse button down.
You have it, if (Input.GetKeyDown(KeyCode.Space)
Hm. Then I think something weirder is going on, because this isn't registering even with debug logging.
And without the conditionals
You've separated them, either you press space and selectedDialogeType == DialogeType.text, OR, it doesnt matter if you press space, and selectedDialogeType == DialogeType.Talk. Is that intentional
too be honest, maybe a better behavior would be spawn at Y location and let it move upwards and fade out over time, then you dont have to worry about offesets
It doesn't matter, both the conditionals are true. Even when removed it doesn't register for some reason..
I need this behavior
I am attempting dotween right now
I feel like you could just use world space UI here and not need the anchored position
Why is that different?
Does anyone understand why ONLY GetMouseButton(0) works and displays its log here?
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Mousebutton Left pressed.");
}
if (Input.GetMouseButtonDown(1))
{
Debug.Log("Mousebutton Right pressed.");
}
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Spacebar pressed.");
}
I'm using the Old Input System - is there something else that could be blocking this?
This is all in Update()
Space doesnt work?
Show the entire script?
Is the script on an active object?
The code is correct theirs something else messing with it
This is the entire update method - like I said the mouse button 0 (left click) works, the obj is definitely active.
private void Update()
{
if (Input.GetKeyDown("space"))
{
OnNextNode();
}
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Mousebutton Left pressed.");
}
if (Input.GetMouseButtonDown(1))
{
Debug.Log("Mousebutton Right pressed.");
}
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Spacebar pressed.");
}
LayoutRebuilder.ForceRebuildLayoutImmediate(TextMessageContainerRectTransform);
}
If you hover over update does it say this?
The rest of this is just JSON serialization and stuff, nothing else to do with input
Do you have any errors in your console
Nothing at all
if you comment out that bottom line will it be ok?
restart the editor, that's the usual fix if it isn't properly detecting your input
No, that just rebuilds a piece of my UI every frame
Actually now that I look at this again, I'm not really sure how this exact code relates to the issue. It looks like this is just for a single object, but the problem you described was for many. Nothing here really shows that initial step where you spawn or get this text object
Yeah, weird. No dice on restart either. Maybe I'll try swapping to the new input system and back to old.
something else is going on here then. are you certain you've saved your code and that it has recompiled after making these changes? are you certain you are using the correct component and that it is on an active object in the scene?
Code compiles completely and has recompiled after changes. I am totally certain the game object is active and enabled in the scene.
This is the only script in which the log for left mouse button exists and it is being called correctly while the others aren't.|
I've also tried other keycodes, like A, T, Backspace - none of those register either.
then there is no reason at all those others wouldn't work unless you're just not pressing the keys or something has fundamentally broken in your project. there are no return statements, no errors in the console (at least in the screenshot you showed) and those are separate if statements so they should work. use the debugger to figure out what is going on 🤷♂️
In another script it spawns it
Unity goblins, probably. I'll poke around some more - thanks!
Did you make sure you save?
😭
what is that 😭
My game uses a phone UI so I had no idea lol (very similar game UI to real iphone)
Simulator is Unity's phone simulation tool.
It doesn't handle keyboard Keycode inputs.
At least, not in Editor as far as I can see.
I am currently having a confusing problem with ink and my quest system. when i speak with the npc the first time, it all works great, i can accept the quest and the dialogue ends. but when i speak with the npc again, it starts at the == QuestAccept== section on the ink text rather than the start for no apparent reason.
Script that displays the dialogue and interacts with ink
https://hastebin.com/share/rujakajoji.csharp
Script thatis part of quest progression
https://hastebin.com/share/isotiqavoj.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Ah, makes sense. Unity interprets a tap as a left click for compatibility reasons, so that'd explain why that was the only input that was working
Fixed it
it should be a law that if you fix something you should say how you fixed it so that people searching a similar issue in the future find what you did instead of just the phrase "fixed it"
yheah i was looking at it to figure out how too 😭
Its looking like if the tween was just spawning in, i adjusted its spawn in end position, but i also never stopped it from still doing the original moveup that others were doing
public void MoveUp(float amount)
{
//Spawning in and another poup spawns in, we have to spawn in higher
if (spawningInTween != null && spawningInTween.IsActive())
{
spawningInTween.Kill();
endPosition += Vector2.up * amount;
spawningInTween = rectTransform.DOAnchorPos(endPosition, fadeInDuration);
}
//If already moving up due to another and another spawns, adjust move up destination to move up more
if (moveUpTween != null && moveUpTween.IsActive())
{
moveUpTween.Kill();
smoothUpEndPosition += Vector2.up * amount;
}
//If not already moving up, our position is just up by amount
else
{
smoothUpEndPosition = rectTransform.anchoredPosition + Vector2.up * amount;
}
//Move from current position, Upwards to account
if (!spawningInTween.IsActive())
moveUpTween = rectTransform.DOAnchorPos(smoothUpEndPosition, moveUpDuration);
}
``` ended up with this
Hey all. I have been studying serializing and deserializing. I got confused at one point. When I deserialize, dont I need some kind of Identification to put the data back into my lets say Player object? or is it enough to just match the deserialize data to my player data? Will it automatically put stuff in my Player?
Generally deserialization will create a new instance if the class being deserialized so you will need to assign that instance to your player ore move the data across manually
anyone know why when i increase my rate my split increases and doesnt decrease
https://paste.ofcode.org/cJiq2RGvkCrupHW64WM6Sy
Ah okay. What about using Id's? Why is there a need to use Id's?
I mean lets say for saving and loading scriptable objects for instance.
Update:
- Terrain now only has the "Tilemap Collider 2D".
- To ensure that there was a collision between the fireballs and the ground, I checked the "Is Trigger" option together with the one that was always active, namely "Used By Composite".
- I created a separate script for fireball collisions: https://gdl.space/kirizuyujo.cpp
But now that the fireballs get destroyed, when they collide with both types of terrain, as soon as I click play, the character starts crouching without being able to get up even though he can move and immediately falls through the terrain.
that is going to be down to what and how you are serializing/deserializing
Hm all right. Thanks a lot!
any1?
hey, can anyone help explain to me why my code defualts the resolution to one that isnt native to my monitor? It happens when i build and run. Here is the code:
anyone? im going insane here
Wdym starts the QuestAccept section? Isn't that behavior intended?
you dont need code to scale resolotioun?
no, it should start at the start. == QuestAccept == should only be used after some dialogue
So when your player interacts with the NPC the QuestAccept is triggering right away?
I am kinda confused tbh i used a tutorial and checked over the code for problems that might cause this but i could not find one. idk if you need code to scale it, it is for a settings menu
considering making my own pathfinding system
i have no idea. i checked everything and it "should" work. in programing class today my prof was also confused, but didnt have much time to check
i have added the scripts i deem most relevant to this in the other pastebins
Can you try breaking it down into a simpler step? When I trigger the player NPC the first time does a variable change?
wdym?
So it works the first time, right? Something must have changed the second time you talk to the NPC for it to behave differently.
yes, because the first time, you accept the quest. and when the quest is already accepted, the dialogue has a different behaviour, however the starting point is identical, it should start the same way, but it doesnt
If I had to guess based on skimming your code it would have something to do with this:
private void HandleTags()
{
if (story.currentTags.Count <= 0)
{
return;
}
foreach (var currentTag in story.currentTags)
{
if (currentTag.Contains("addQuest"))
{
var questName = currentTag.Split(' ')[1];
var quest = questConfig.quests.First(q => q.GetId() == questName);
GameState.StartQuest(quest);
// FindObjectOfType<QuestLogView>().ShowActiveQuests();
}
if (currentTag.Contains("removeQuest"))
{
var questName = currentTag.Split(' ')[1];
GameState.RemoveQuest(questName);
// FindObjectOfType<QuestLogView>(true).ShowActiveQuests();
}
}
}
Hmm maybe not... hard to tell without touching it myself
hey guys, can someone here explain me what an abstract class is, and what it means to implement a class?
thats exactly what i thought too, then i added a debug log with quest information and that part works like a charm
Hmm, what other possibilities have you considered?
currently my suspect is this section
{
FindObjectOfType<PlayerInput>().enabled = false;
gameObject.SetActive(true);
story = new Story(textAsset.text);
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
foreach (var quest in GameState.GetCompletableQuests())
{
story.variablesState["finished_"+quest.Quest.GetId().ToLower()] = true;
}
foreach (var quest in GameState.GetActiveQuests())
{
story.variablesState["started_"+quest.Quest.GetId().ToLower()] = true;
Debug.Log("Queststarted is true");
}
ShowStory();
}```
because that debug log does not trigger (it should trigger the second time)
That's likely your bug then, no?
if it is, i am unable to figure it out. i ve been sitting infront of those lines for hours and idk whats wrong
Have you tried using the debugger?
Where it isn't being triggered, and inspect the variable in question
yes, but the game doesnt actually recognize anything wrong, atleast debugger gives me nothing
Interesting
Let's review, so your quest dialog appears on the second press which is unintended, right?
Second interaction*
yes
the red is what happens the first time, the blue is what should happen the second time, but the yellow is what actually happens
Oh I see understand your problem
Interesting
Well something is causing [0, 1, 2] to bypass 1 if I understand how you would arrange dialog like this
wait a second. i ll try something
Hello! I have a question about displaying health on Unity 2022 LTS. This is the code I used for 2018 to display health but this same code doesn't work on 2022. There must be some change I don't know about with the version. Also I am new to 2022 because I used 2018 for 2 years in college.
your text object is more than likely a TMP_Text (or more specifically a TextMeshProUGUI which inherits from that) rather than the legacy Text object. of course you'd be receiving a NullReferenceException at runtime if that were the case and surely you'd mention if you had errors 😉
the two separate health variables are also kind of redundant, and the GetComponent call every frame is pointless when you can just store the reference to the component instead of referring to its gameobject to then call GetComponent on that
Thank you so much I did it! lol
try this one healthDisplay.GetComponen<Text>().text = "" + internalHealth;
idk why would u need to assign it and not use
It's for a game I am making. There will be an enemy that will damage the player and the health will start at 100 and go down when the player gets near the enemy
is that " " there to avoid typing ToString? 😄
Listen I learned a lot of my coding from Jimmy Vegas 😆
Uh, who is that?
I have no idea what a Jimmy Vegas is but you should just use ToString
He does tutorials for Unity
Tutorials for making games
His videos helped me learn C#
I'd definitely cache that GetComponent though . . .
the entire GetComponent is unnecessary if they just make their healthDisplay variable the correct type
Also true . . .
yes, you should just assign a reference to the text component directly
GameObject is almost always the wrong type.
hey guys, can someone here explain me what an abstract class is, and what it means to implement a class?
It's a class you inherit from like a normal class, but it is necessary to inherit from it. You cannot use it directly
what do you mean by inherit?
An abstract class is a class that you cannot have any instances of, but you can extend it. For example, there's nothing in nature that is an Animal without being like, a cat or a lemur or a tardigrade or whatever. Cat is a type of Animal, but there's no such thing as just an Animal.
an abstract class is too vague to exist yet
but it can still have qualities of its own
a common thing I wind up doing is something like this
public abstract class Scorer {
public abstract float GetScore(Item item);
}
public class ValueScorer : Scorer {
public float GetScore(Item item) {
return item.value;
}
}
public class ConstantScorer : Scorer {
public float GetScore(Item item) {
return 4;
}
}
every Scorer can give you a score for an item
I'm using 2d unity to make a game, when my rigidbody touches the ground object and i try to move the value barely increases, and the value just kind of spasms if that makes sense, changing the decimals very slimly back and fourth
but I can't create a Scorer
(this is a case where you could just use an interface, of course -- but you can also have abstract classes with some concrete code in them!)
What value
every Animal has a name, for example, so you'd put a name field in Animal
speed is set to 10
So speed goes up and down?
Oh no, the x and z value does
📃 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.
hmmm, I think I understand better, but can you just explan to me what the diffrence is between a normal class and an abstract class?
Best to show how you move the object with code . . .
Abstract classes can contain abstract members, and you can't instantiate an abstract class.
An abstract member has no implementation. Child classes must implement it (or also be abstract)
That's pretty much it.
(jumpheight is for future)
using a box colider and a box colider for ground
you can declare but can't implement methods in abstract classes
First of all, don't multiply velocity by deltaTime
Edit: yeah, just try fixing that first
im sorry but what is a Child classes?
you really need to read this #💻┃code-beginner message
At this point, it's better to watch or read a tutorial instead of receiving one here, albeit in broken messages . . .
you need to learn a lil of oop
When do you wanna use it?
When something needs to be consistent across frames, something that isn't already.
Velocity is already. It is meters per second
OOP (Object-Oriented Programming), which is where you derive from another class or interface for a more... modular approach
Oh nvm im dumb, thank you for your help, I thought it had something to do with the grounds friction (like in 3d)
It does not have to do with friction in 3d.
It is literally just the amount of time since the last frame
No I meant like, once it did for me when I had an issue with movement. The cube just got sent flying because of it, rather than it being smooth. I thought it was something simular
Sorry im probably giving you brainrot with my explanations lmaoo
It's all good
i get this error even tho i dont have any missing scripts on that gameobject?
You may have deleted a script recently that is still present as a "missing script" on a gameobject
I usually encounter this error after deleting a script or storing a field reference to a script that no longer exists
Look through all of your gameobjects one by one and check for a missing script, and consider restarting your editor / reloading domain.
i moved and deleted some scripts but they arent related to network runner objcte in any way
There is 100% a reference somewhere that is no longer functional
It is up to you to find it.
If the problem is "My toast is burnt but I cooked it perfectly", perhaps the assumption is flawed?
i cant find it.... lmao in my scripts on the object i just checked all referenced scripts are present
im wondering why ToBlue doesnt work. i checked and the skin has the right info. I am changing a skin of a 2d character in ToBlue, maybe i need to change something else. btw i change the animator because the skin changes when it jumps
Reload domain, restart editor, check every game object, and check the inspector window for every game object thoroughly. Check the fields of EXISTING scripts for missing references.
What is the value of blue
And is as RunTimeAnimatorController redundant? The highlighting in your editor makes me think it is. Mouse over it and check the context actions.
public AnimatorOverrideController blue;
oh lol i opened this object prefab and it actually has a missing scirpt
it is
it means you can remove it with no errors
This is not a value, is it?
This is a variable declaration
like public float myFloatNumber
What is the actual value of that variable, and is it compatible with the property you're setting equal to the value?
i put the animator override controller
figured it out, as always its a highercase lowercase mismatch and the debugger couldnt catch it because ink text is in a seperate file
of the blue version of the skin
First off, have you put a debug log in ToBlue to ensure it's even running at all?
yeah it doesnt even run
do you have errors in your console? those Find calls then the GetComponent calls can absolutely fail and cause the following code to not run
nope
then you need to debug your condition for calling the ToBlue method
Then that would be a good indication as to why it doesn't work
the skin data doesnt stay the same after i switch scenes
Is it supposed to? What's making it do so?
yeah in the shop when you click a button i call
public void JsonEquipSkin(int equipSkin)
{
info.skin = equipSkin;
string SkinInf = JsonUtility.ToJson(info);
string filePath = Application.persistentDataPath + "/SkinInfo.json";
System.IO.File.WriteAllText(filePath, SkinInf);
Debug.Log(SkinInf);
}
so json file
and are you loading that when you switch scenes?
Are you sure you're reading that data back before you attempt to read from it?
specifically before this code runs?
Awesome! Great work
how do you load it
you read the file then deserialize the contents. pretty much the exact opposite of what you are doing in JsonEquipSkin
yeah i think its the fact that it creates a new one probably when i check because i reference data = SkinInfo.info and not data = SkinData, but i cant reference SkinData because it doesnt derive from monobehaviour.
again, you need to deserialize the saved data when you load a new scene
so the current reference is alright the one where i reference new skindata?
after you deserialize the data you assign it to your variable
if(a != null || b != null)
is a statement like this going to run ONLY if one or the other is true, or will it still work if both are true?
^edited to make it simplier
it will run if either one is true. that includes both. in fact if the first is true it won't even evaluate the second
thank you
If you want it to run only when exactly one of the two is true you'd write:
if ((a != null) != (b != null))``` which looks funny but less so if you just use placeholders:
```cs
if (x != y)```
There's also XOR, which is ^. if (a ^ b) will run only if exactly one of the two is true
I'm using the new input system yet I'm lost on how to debug whether or not I am receiving input correctly in the first place. Any insights appreciated
private void Move(Vector2 direction)
{
if (CanMove(direction))
{
transform.position = (Vector3)direction;
}
}
I guess my question is how do I know the script is receiving input to begin with? Do I use a Debug.Log? Or do I look at this debugging tool shown above
u can debug log direction..
or in that debug menu u can find the keys u use.. and watch for them to change..
it'll go from 0 to 1 when the key is being pressed
Well of course that is working but I am trying to debug whether or not it is communicating with the script, I'll try to Debug.Log the direction and see what happens
ya, thats the first thing u should try
Yeah it's shooting a blank
is the action set up correctly?
It's my first time doing it, so I'm not entirely sure
and do u subscribe to it and all that jazz?
im not too familiar with it but im trying to learn as well
Pretty sure I've mapped out the keys correctly
But we need to know whether or not it is firing to be extra sure
can u show ur input script?
The PlayerController.cs? Sure
not the generated one.. but the part where u assign direction
What's super confusing is that it generates all these files like InputSystem.input, PlayerMovement, etc.
heres how mine looks for context
private void OnMove(InputAction.CallbackContext context)
{
Vector2 movement = context.ReadValue<Vector2>();
Debug.Log($"Move: {movement}");
}```
my move function looks liek this
On a cursory look they seem similar
and no console errors?
None
Code looks correct. If you're not getting the log, then the if statement on line 41 did not succeed. Try placing the log outside of that
Like I said I think what's happening is the input system is not firing, it's probably registering my key stroke, but not communicating that with the script
Also log in Awake, OnEnable, Start
i meant here... but i was thinking it probably is if it let u make an action map
id try loggin in other functions like spr2 mentions too
im just brain-storming b/c im new to it as well
No worries, let me take some time here and see what I can do
I think this video might offer some insights into debugging the new input system
https://www.youtube.com/watch?v=ICh1ZEaVUjc&t=2s
Learn how to debug your input using the Input Debugger! See all of your controls and their current values, debug remote devices, and visualize your current action values!
ᐅGet the full Source Code Bundle to my Unity Tutorials 🤓
https://sam-yam.itch.io/samyam-full-source-code-to-all-videos
🤝 Support Me 🤝
Patreon: https://www.patreon.com/samyg
D...
I'll try some stuff and report back
Those functions are working as intended
no, log the input in those i think is what he meant
Start isn't logged though
lol
That's where you tell the input action to notify you when it's triggered, so it's pretty important to ensure it's executed
Now place a log in Move() but outside the if statement. If you get the log (when making inputs), then it's the if statement that fails
Like this?
private void Move(Vector2 direction)
{
Debug.Log("Move");
if (CanMove(direction))
{
transform.position = (Vector3)direction;
Debug.Log("Direction" + direction);
}
}
Yep
You're right, the input is failing
Saved me 20 minutes of watching a debugging video
The input is there
Yeah
the if conditonal isnt being met
It's your CanMove() function that's returning false
We don't need no fancy tools just logic 😂
The player appears to be moving incrementally but stuck, for example when I press the S key twice it won't move the number further
it's like they're stuck in one grid cell or something
Make sure both tilemaps are perfectly aligned. Since you only get the position from the groundTilemap but feed it both to that and collisionTilemap, the method won't work correctly if groundTilemap and collisionTilemap aren't perfecly superimposed
I see... so what is happening is despite there being a tile it registers as false no matter what is pressed. Interesting...
On it
If I'm reading this correctly they are in fact, superimposed
An alternative would be to duplicate line 50 and change it to get the position on the collisionTilemap, so you have two distinct position variables relative to each tilemap
I'm not sure I quite understand that solution
Let me think about it for a second
Oh I see get the collisionTilemap instead of groundTilemap
Still won't budge
OH WAIT
Let me try something
Nevermind I thought disabling the player's collider might do the trick
But I would need it in the long run anyways
You'll need to modify your code so you can debug all these position values calculated from the tilemaps, as well as the results of both HasTile() calls
Okay on it
Wait the result of HasTile is always false right now, we wrote debug calls for that
private bool CanMove(Vector2 direction)
{
//Vector3Int gridPosition = groundTilemap.WorldToCell(transform.position + (Vector3)direction);
Vector3Int gridPosition = collisionTilemap.WorldToCell(transform.position + (Vector3)direction);
Debug.Log("gridPosition: " + gridPosition.ToString());
// If either the ground does not exist or ground does exist but has a collision
if (!groundTilemap.HasTile(gridPosition) || collisionTilemap.HasTile(gridPosition))
{
Debug.Log("False");
return false;
}
else
{
Debug.Log("True");
return true;
}
}
Do you think it could have anything to do with the initial starting position of the player?
Which one of the two returns false/true? Note that you have a ! on the first one
Darn Unity isn't letting me type in the inspector rounded values...
It translates to: if there is no ground tile or there is no collider return false
For the method to return true, there needs to be a tile on the ground map AND no tile on the collision map for the specified position. One of these two aren't returning the value you expect
Log both return values of HasTile, separately
The code can be simplified down to the following btw:
// On ground and no collision
return groundTilemap.HasTile(gridPosition) && !collisionTilemap.HasTile(gridPosition)
Yep so at that position it's detecting a tile on the collision map
Oh when it's empty it registers the WHOLE tilemap as a collider
Why I didn't put an object for testing is beyond me
Hmm even with an object it's still making the whole tilemap a collider
Is it a setting?
HasTile doesn't care about the collider, but rather whether there's a tile at the position you specify
Disabing the collider entirely should have no effect on the result of HasTile [citation needed]
Oh right....
Why does your tilemap have a rigidbody? Is that standard when you create one? Seems weird
the composite collider requires it
Let me delete Collider Tilemap and remake it, maybe there's something weird happening I can't see
Right, and the tilemap collider requires a composite collider I guess
Nope still won't budge
it's not required, but it does make it perform as one singular collider instead of a bunch of smaller ones
I knew I had a reason to be scared before changing my old movement system to this new fancy one 😂
Trying to fix what was only slightly broken haha
Take the Vector3Int value containing the position of the tile on the map from the log, and manually locate it from the scene view
Imo, it's better to learn the new one . . .
Well it's not the new Input system that's causing trouble, it's me trying to move my character in a perfect grid that's causing the headache
Okay let me try that
In the last screenshot you posted, your player is located between two tiles, usually it should be at the center of one, otherwise transform.position might just be low/high enough for WorldToCell() to mistakenly locate you in the cell directly to the left/right of your player
Yeah I was thinking I needed to fiddle what that value
But freakin' Unity won't let me type values so I can't get a perfect .5
Let me restart the editor see if that does the trick
Fml even with the player perfectly centered in the grid he won't move a damn
Swearing under breath ensues
Wait the issue is pretty simple, there's always a collisionTileMap tile for some reason
But even when I disable it, it still results in true
More swearing
disabling it does not remove the tiles so i imagine that the HasTile method will still return the same value
Maybe it doesn't care if the object is disabled, as it's not a physics call per se
Move the tilemap away, or delete it completely
Prefer moving it, otherwise you'll get a NullReferenceException in your code
or disable the other one and see what tiles are actually set on the Col tilemap
Maybe it's completely filled with tiles indeed lol
Remade the collision tilemap just to be extra sure and no dice, it's not filled
Is there a way to hold (for 100ms) and drag an item in inventory slot? I'm using event system (ipointer) and not new input system
when u click start a timer.. once timer > 100ms allow drag (move image to mouse position)..
if u ever release reset the timer
So now we're getting True, which is definitely a step in the right direction. Yet he still refuses to move. 🤔
input works 👍
are you intending to use sqlite from Unity.VisualScripting.Dependencies in your BirdScript?
then remove line 4 of BirdScript
also for future reference, always start from the first error in your console. the top one is what caused the bottom one
wdym?
oh nvm'
I got it
what was not clear about what i said
I'm just dumb, nothing ty smch for the nearly instantanious answer
expect to hear back from me 😭
Is it possible I need to tell my script what transform.position to move despite being attached to the player?
private void Move(Vector2 direction)
{
//Debug.Log("Move");
if (CanMove(direction))
{
//Debug.Log("CanMove");
transform.position += (Vector3)direction;
Debug.Log("Direction" + direction);
}
}
No. If that script lives on your player, then using transform.position refers to that immediate object
if that log is printing then that object is being moved. which means if you see it constantly in the same place then something else may be affecting is position, this could be code, or something like the animator controlling its position
Oh my goodness I am so dumb.
I'll show you what was happening
Celebrate good times.
In retrospect I should printed the position of the player somewhere along the line
Hello I am currently following Japser Flick's compute shaders tutorial(I'm not aware of how well known catlike coding is) and this is my first time writing shaders, I get a Kernal Index (0) out of range error. I looked this up and apparently that means the shader didn't compile. Also in my project the compute shader appears as a text asset with a compute shader inside of it? I haven't seen this anywhere else and am wondering if it is related to my error and for some reason unity isn't recognizing the shader as it is supposed to. When I look at the compiled code, theres not really anything in there it says "**** Platform Direct3D 11:
no variants for this platform (no compute support, or no kernels)"
Also !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I am making a 2d character controller, and I am using addforce to move the player but the player never stops.
Changing the friction makes the player stick to walls, adding drag makes the jump buggy, and if I used rgidibody2d.velocity instead it would prevent other forces like dashing or walljumping
this is the movement code:
rb.AddForce(new Vector2(direction * speed, 0), ForceMode2D.Impulse);
can you add to velocity? you don't have to set it directly
that speeds it up if I keep adding the movement velocity
rb.velocity = new Vector3(rb.velocity.x, rb.velocity.y + 100, rb.velocity.z)
something like this
idk if you can just do
rb.velocity += Vector3.up
but maybe
that would work for jumping but for movement it would keep speeding up
can you just clamp the velocity after setting it
or does that interfere with dashes?
sounds like you want a damping force
Maybe consider using something other than the Rigid body component if Rigid body physics isn't wanted. A non physics controller option would be the Character Controller component. There are also controller assets in the asset store that might be useful such as the kinematic character controller but it's quite complicated.
the vast majority of games do not use phyiscs for character movement
it just does not offer enough control and fine tuning
Gravity isn't enough to justify a rigid body component 😅
you can still drive your rigidbody so it can push other physics objects around and detect events so you know when to prevent movement
but where its movement is all in your logic
like OnCollisionStay or something?
right now how this script works is by checking for a click from the player which calls the gamemanager.OnClick method which then starts a timer to check when the player can click again. instead of the gamemanager.OnClick function being called when the player clicks, how would I call it after the timer check has been completed?
So you don't want it to be called on click or do you want it to be called on click only after the initial elapsed time?
I'm assuming you're only wanting to process the on click events after the elapsed time has been met. You'd do so by encapsulating whatever's in the on click method with some if statement. Here's an example using your interactable button state https://hatebin.com/gwqwiwttcy
blue box is a trigger, what's like the best way to let it decide what direction to turn to?
it rotates like this btw
You'd decide which way it'd turn. I'm not sure what your question is.
Curious to let it smartily decide to turn to left if the asteroid is on the right side of the trigger
and vv
I mean you can check this with some simple math
current direction is to use 2 triggers, but that's not really fun
Hi there, I'm facing an issue I really don't understand since I've found SOOOO many intel that clearly says that I'm not doing anything wrong so maybe I'm false but I'm total lost rn.
I'm using enums to allow multiple mobs to "recognize" other mob "types (e.g. hostile, peacefull) and mob "species" (e.g. spider, plant). Since enum cehcking can starting to be pretty uglywhen checking for many mob types and species, I want to use Flag enum to allow multiple choices (e.g. TargetMobType = Hostile | Peacefull)
Now problem is that when I'm in the inspector setting those "filters" I definitely can't since when I'm choosing one possibility, the variable is randomly set to "Everything" or "None", and an out of bound error is fire.
Got any idea about that ?
You could circle cast and direct your box towards the nearest threat(s) or some other algorithm to direct the box towards groups of enemies - spatial partitioning with quad trees or whatever.
I have a game that I'm making that works like this. 0 gravity basket ball in 2d basically. I have set up multiplayer but am struggling figuring out how to let everyone interact with the ball (being able to grab and throw it) At the moment I have it so the ball can be grabbed and thrown by the host, and so that everyone else can see the ball but not interact.. Wanting direction as to where I should look, at the moment been trying to serverRpc but not sure if I should keep trying or do something else.. Here's how I spawn it in currently:
if (Input.GetKeyDown(KeyCode.B))
{
SpawnBallServerRpc();
}
}
[ServerRpc]
void SpawnBallServerRpc()
{
Ball = Instantiate(BallPref);
Ball.GetComponent<NetworkObject>().Spawn(true);
BallRB = Ball.GetComponent<Rigidbody2D>();
BallNetworkObject = Ball.GetComponent<NetworkObject>();
BallNetworkObject.ChangeOwnership(NetworkManager.LocalClientId);
foundBall = true;
}```
and some other stuff I've tried implementing
```c#
[ServerRpc]
void HoldBallServerRpc(Vector2 handPos)
{
BallRB.MovePosition(handPos);
}
[ServerRpc]
void SetBallVelServerRpc(Vector2 vel)
{
BallRB.velocity = vel;
}```
And some other stuff for when I grab the ball
```c#
else if (HoldingOntoBall && foundBall) {
Debug.Log("Holding");
// Move the hand to the desired position
HandRB.MovePosition(towardsPosition);
//Move the ball via server rpc
HoldBallServerRpc(HandRB.position);
// Calculate velocity
Vector2 velocity = (towardsPosition - BallRB.position) / Time.fixedDeltaTime;
Vector2 clampedVelocity = Vector2.ClampMagnitude(velocity, MaxBallVelocity);
//Set Velocity
SetBallVelServerRpc(clampedVelocity);```
Let me know if I need to include other important parts of the project I may have over looked. Thanks in advance for at least reading this 🙂
so i have my code and for some reason i want the bullethole effect to not show when im in my reload animation. i have been following a tutorial and when this problem occured i have been searching for a solution for days. when i have my reload animation playing and i click the bullethole effect shows and i dont want that. https://pastebin.com/xjSFJCTD
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.
How to post !code
Post the error.
📃 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.
📃 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.
IndexOutOfRangeException: Index was outside the bounds of the array.
UnityEditor.MaskFieldDropDown.DrawGUIForArrays () (at <78fe3e0b66cf40fc8dbec96aa3584483>:0)
UnityEditor.MaskFieldDropDown.OnGUI (UnityEngine.Rect rect) (at <78fe3e0b66cf40fc8dbec96aa3584483>:0)
UnityEditor.PopupWindow.OnGUI () (at <78fe3e0b66cf40fc8dbec96aa3584483>:0)
UnityEditor.HostView.OldOnGUI () (at <78fe3e0b66cf40fc8dbec96aa3584483>:0)
UnityEngine.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 parentTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout, UnityEngine.Rect layoutSize, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <f6650f702d1247c2a5311a89b759ba03>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
sorry about that
np
when I'm choosing one possibility, the variable is randomly set to "Everything" or "None", and an out of bound error is fire
Do you've got some editor script modifying the behavior of the Inspector?
Hopefully this video embeds
No that I am aware of but it like its working with an empty script with only enum type variable declared
Can you post the code #💻┃code-beginner message
This class inherits from NetworkBehaviour, inspector might be modified there idk
Use gdl or hatebin to post the contents of the script.
As you can see on these screenshots it even make the last choise disapear and selected value is not the same.
The first screenshot is an empty script with only 2 variables of enum types
and it works like a charm
plus you can see that the display of the list is quitte weird
You've got something happening on validate which would occur when changing stuff from the editor.
I'm using KBCore.Refs to automatically assign serialized private properties instead of drag n drop from the inspector could this be related ?
private void OnValidate()
{
this.ValidateRefs();
}
[SerializeField, Self] private NetworkObject m_networkObject;
Comment out that statement and see if the error/unwanted-behavior goes away.
[Space(20)]
[SerializeField, Child] private Animator _animator;
[SerializeField, Self] private SphereCollider _detectionCollider;
[SerializeField, Self] private CapsuleCollider _physicalCollider;
[SerializeField, Self] private NavMeshAgent _navMeshAgent;
[SerializeField, Child] private AttackPoint _attackPoint;
OK !
If it goes away but you'd still like to use it, you may need to consult the dev who wrote it.
Nop still identical, I even removed include statement, could it happen because it stored inside a serializable class ?
Nope I've tried moving the code out of the class and still not working lmao
Does it do it if you give the enums a None = 0
Yes I've even tried giving an Everything = xxxx | xxxx | xxxx | xxxx,
I don't believe enum flags are an issue with the Unity Inspector. Maybe it's something to do with the custom editor KBCore. Seems KBCore is doing some reflection or whatnot with your class: https://github.com/KyleBanks/scene-ref-attribute/blob/main/SceneRefAttributeValidator.cs
What Unity version is this 🤔
It could do that even without being included in the class ? Because I removed it and still no progress
I've got no clue 😅
We're using 2022.3
Ahah no problem thanks for trying to help !
You could probably test the enum flag with a new blank script and whatnot to verify that it's nothing to do with KBCore.
Yes that's a great idea actually
Works fine on my end
KBCore or enum flags 😅
No idea what KBCore is; the enum
Working well with KBCore even when it modifies the inspector
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using KBCore.Refs;
public class Test : MonoBehaviour
{
[SerializeField, Self] private Animator _animator;
public TypeOfEntity EntityType;
public Species Specie;
public void OnValidate()
{
this.ValidateRefs();
}
}```
If this isn't dark magic I don't know what it is
It's reflection acquiring some fields with attributes from some type that likely has a value not within bounds of your actual field/type.
Could it be because I'm already using LayerMask ref in the class ?
errors will usually stop later execution of code so it could be something totally not related to the enum
Ok so now my IDE event prevent me from writing new scripts wtf
Definitely here :
Could it be related to a Library error ? Because I had to deleted and generate project library earlier today
well yesterday now
I have to go to sleep, I'm since 12am yesterday and its 6am here, Ive encountered many more problems while trying to edit other scripts, @timber tide might be right I may need to check for missing dependancies idk will se in few hours. Many thanks for your time @ivory bobcat & @zenith cypress
Is update expensive? I've been using mostly coroutines
void Update()
{
if (active) // do something
}
Don't worry about premature optimizations - use the profiler when necessary.
Just to answer your question though, a bool check every frame isn't expensive.
Thanks :)
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
!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.
if (fillMode && _currentMode == Mode.Terrain)
{
_stopwatch = new System.Diagnostics.Stopwatch();
StartCoroutine(FillWithinPaintedAreaCoroutine(x, y,Map.instance.mapSize[0], Map.instance.mapSize[1]));
}
-------------
private IEnumerator FillWithinPaintedAreaCoroutine(int x, int y, int maxX, int maxY)
{
if (_stopwatch.ElapsedMilliseconds >= 200)
{
yield return null;
_stopwatch.Reset();
_stopwatch.Start();
}
if (x < 0 || x >= maxX || y < 0 || y >= maxY) yield break;
if (Map.instance.GetBiome(x, y) == (Biome)_type) yield break;
Map.instance.SetBiome(x, y, (Biome)_type);
UpdateTile(x,y);
// Recursively fill neighboring pixels
yield return FillWithinPaintedAreaCoroutine(x, y + 1, maxX, maxY); // up
yield return FillWithinPaintedAreaCoroutine(x, y - 1, maxX, maxY); // down
yield return FillWithinPaintedAreaCoroutine(x + 1, y, maxX, maxY); // Right
yield return FillWithinPaintedAreaCoroutine(x - 1, y, maxX, maxY); // left
}```
Hi guys! I've been struggling to grasp coroutines a bit q.q I want each frame to spend a max of 0.2 seconds filling in tiles but I believe this keeps pausing on every single tile? How do I go about making the coroutine correctly?
is it a good idea to inherit from GameObject in unity?????
or am i only supposed to inherit from MonoBwehaviour
i am trying to create a complex trees of objects
Hello, I'm trying to extend the dropdown to a multi select dropdown.
{
private List<int> selected = new();
public bool isMulti = false;
}```
But the isMulti bool does not show in the editor in normal mode. It does show in debug mode. Why is that ?
I don't see why you couldn't inherit from GameObject
!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.
also another question
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ball_mechanism : MonoBehaviour
{
public GameObject Ballstart;
public GameObject Ballend;
public static bool isDone;
public static bool canPlayAudio;
public static int score;
void Start()
{
isDone = false;
//canPlayAudio = false;
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag(gameObject.tag)&&isDone==false)
{
Vector3 spawnPosition = collision.gameObject.transform.position;
GameObject newObject = Instantiate(Ballend, spawnPosition, Quaternion.identity);
//Destroy(GameObject.FindWithTag(gameObject.tag));
Destroy(collision.gameObject);
Destroy(Ballstart);
score++;
canPlayAudio=true;
Debug.Log("destroyed" + score);
isDone = true;
Invoke("DelayedDone",0.5f);
}
}
public void DelayedDone()
{
Debug.Log("i set the bool to false");
isDone=false;
canPlayAudio=false;
}
}
why is invoke not working
it is working on code simmilar to this
You get the first log "destroyed" + score correctly ?
yes
but no debug for invoke
You'd use a coroutine to yield (prevent execution) for a duration of time, not to execute operations a certain amount of times per frame. If you're wanting to evaluate time between instructions, you could use a comparison of time stamps using Time.time, C# stop watches with the elapsed property https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch.elapsed?view=net-8.0 or whatnot.
But isn't that exactly what my stopwatch does?
Weird, I don't see any issue with your code.
Are they sure it's not being called twice and they just have the console collapsed?
i have 2 code similar to this, one gives debug in invoke but this one didnt print any debug
I'm uncertain but it wouldn't require a coroutine (unless you're trying to continue execution of instructions where you'd last left off - which you might be with those recursive yield statements below, now that I think about it).
Is there an unwanted behavior that you're seeing?
Well it seems to constantly be pausing it every frame rather than every 0.2 seconds
Log how much time has elapsed before returning null
if i want to change position of a game object i need to use gameObject.transform.postion
is there anything similar for velocity? i know of rigidbody component which should have .addForce --> moves body via forces not velocities (more realistic)
which approach better:
-
create a separate
_velocityfield in my component and move my game object viacomponent._velocity += component._acceleration / component,_mass * Time.DeltaTime -
or should i add
rigidbodycomponent and use itsaddForceto move it
and if rigid body is a better approach, should it be added to an empty game object ? i mean won't anything colide with it ? even if it doesn't have a mesh?
If it states 0.2, then we would assume it's working as intended - excluding not accounting for time between frames.
But this is what I mean, I'd expect this map to be like updating every 0.2 seconds, but it's updating constantly like a stream, which makes me think that the frame stops after every tile
Is the recursive yield at the bottom where I yield on each function call, not causing it to pause every call?
I know I am updating a texture but I wouldn't see that unless a new frame came right? Because the renderer would be waiting for the frame to finish
Log before yielding null the elapsed time - no they ought not be stopping the coroutine (simply a function call)
Better yet... If I completely comment out the stopwatch / yield bit there, it still acts the exact same way
I'm not sure what your question is but the yielding function would finish before the other yielding functions are called.
Assuming you're wanting all recursive functions to be called within a single frame
I'm not sure how else to word it... The coroutine appears to be constantly yielding, so basically every 1 frame, it updates 1 tile and this is insanely slow...
I want it to do as many tiles as it can in 0.2 seconds before it yields and then continue to do as many as possible
Look at how slow this is because of it yielding none stop
The video is 4 seconds, so we can only verify that it's filled quite a few pixels by 4 seconds. How many per seconds, we would not know unless you somehow verify the number of iterations that are occurring and how many milliseconds have elapsed between each yield of null.
How can I verify it?
2 ways
- I removed the stopwatch completely so now there is no stopwatch there to yield it, so it is constantly yielding without a stopwatch
- My eyes? You can see the FPS of the video, if it wasn't yielding none stop, the FPS would be way lower
Frames are not being slowed down at all... so it's needlessly handing control back to Unity none stop
You need to count how many pixels are filled per iteration - it could just be the writing to texture is slow etc
Number 2 is an assumption.
Look even if that is the case... Which probably is a factor and I can optimise in the future, it doesn't change the fact that it's yielding none stop