#💻┃code-beginner
1 messages · Page 65 of 1
thats how these things go
why is it trying to rotate towards 0 in the first place n all that
true, had a zero check from before that i used here,
isWalking = moveDir != Vector3.zero;
float rotateSpeed = 10f;
if (isWalking)
{
transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotateSpeed);
}
like this
You might wanna use MoveTowards (whether vector3 or quaternion). The lerp doesnt make a lot of sense, since the rotate speed here is not actually gonna be what you think it is
And I think there might be a (extremely rare) chance that this still produces 0. If your vectors are pointing in opposite directions and third parameter is 0.5, then itll the resulting vector would be between both at 0,0,0
Hey can anyone explain what im doing wrong with polymorphism? So I have a ScriptableObject Item, and I have Consumable inherit from Item. In my Item script i made it an abstract class with the abstract method OnUse(). In my Consumable script I have a field for a Consumable script, and have an override OnUse() method where I call the consumable reference OnUse() . Then I made a Medkit script that inherits from Consumable and overrides the OnUse() function but for functionality I want the Medkit script to inherit from Monobehavior but I know Unity doesn't support multi-inheritance. I'm sure I'm not doing it correctly what should I change and why?
In my Consumable script I have a field for a Consumable script
This part I don't understand
Then I made a Medkit script that inherits from Consumable and overrides the OnUse() function but for functionality I want the Medkit script to inherit from Monobehavior
It can't be both a MonoBehaviour and a ScriptableObject, that doesn't make sense
Can I ask why Item is a ScriptableObject in the first place?
Also you may want to consider that there's two pieces to this:
- There's the item description which is a scriptable object that contains some static data.
- There's the in-game representation of the item, which may be a MonoBehaviour.
if you have both of those you'll need to split those up
There may even be more representations of the item in your game too - for example displaying the item in the inventory vs on the ground in the world
So the reason why I want it to be a scriptable object is so that I can create an asset for different consumables that all share common properties. And my thought process for having a consumable field in the consumable script is because all the scripts I planned to add for the consumables were supposed to inherit from the consumable script.
but then it cannot be a monobehaviour
What you may want is:
- A ScriptableObject called ItemDescription which maybe has an icon, some stats, etc.
- A MonoBehaviour called Item which has a ScriptableObject reference, this represents the item in the world
- If you have an inventory it can deal with ItemDescription directly
Monobehaviours get instantiated during runtime
consumable field in the consumable script is because all the scripts I planned to add for the consumables were supposed to inherit from the consumable script.
This doesn't clarify anything. Why would you need such a field?
I have problem where my player goes through walls even though the walls have colliders
check collision matrix, layers of each object, layer/force overrides, and rigidbody type
show the inspectors for the player and wall
Gotcha so because the the functions are very different I'm better off creating multiple classes to handle each specific thing? So for example an Item Monobehvaiour and ItemSO that the Monobehaviour will reference the data. Then I can have the functionality ex. Medkit or StaminaRecovery functinality inherit from that monobehavior where my Item script will call that function?
it really depends how the functionality works
assume you only have 1 instance of an SO for a kind of item
Inheritance is not necessarily the right move here
if you have Consumable : SO, then in pokemon, I would expect a single Potion.asset, HighPotion.asset, and MaxPotion.asset in the entire project
I often end up with a system like:
public class Item : ScriptableObject{
public List<Effect> effects;
}``` and then make Effect configurable in the inspector in a pretty flexible way
then I would have Item as a POCO, with a field for Consumable for the one consumable it corresponds to.
And Inventory : MonoBehaviour which might have like a List<Item>.
the list might have multiple items that each reference a common SO
like 4 different entries in the list where the Item’s Consumable field is Potion.asset
oh, then how would you go about making a variety of different SO? so for example the pokemon potions all do the same thing just different textures, stats, etc. but they all have the functinality of healing pokemon. What if say I wanted to make different effects. So some consumables heal health at varying degress, but another consumable may increase speed?
Your player's Rigidbody is kinematic. Kinematic bodies do not respond to collisions, obstacles, or forces
It's also unclear how you're moving the player in your code.
i changed it to dynamic and i can show you the code
once you write an SO, you need to create an asset that is tied to it. Like [CreateAssetMenu()], then right click in assets to make a new .asset tied to that SO
yes show the code
this doesn't show us anything. You're just modifying some variables here, not moving anything.
so I can define Consumable : SO, and then right click to make 10 new .asset files, which are all tied to the definition of Consumable
!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.
share the full script
You are moving by directly setting the position: transform.position = new Vector2(x, y);
this will ignore physics entirely
you need to move via the Rigidbody if you want physics to work
for pokemon, I would make Item : SO, and HealingItem : Item
oh okay thank you ill try that
so all the potions etc could have a specific field for healing value, and you wouldn’t need to have that field for an XAccuracy or so
but all items need to be managed by the inventory system
Rigidbody2D rb;
void Awake() {
rb = GetComponent<Rigidbody2D>();
}
void Update() {
Vector2 input = new(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
rb.velocity = input * 5;
}```
for example^
yea im trying to make borders
for the borders you can use colliders
aka invisible walls
so that the player cant pass trough them
yes those are called colliders
Wait okay I understand this, and why you did it. But now i'm wondering how do you add the actual healing function to the HealingItem script. Since its not able to inherit from monobehavior.
because the SO doesn’t do anything. It’s a monobehaviour that does
Shop : Monobehaviour works with all sorts of items, to modify Inventory (POCO or Monobehaviour)
BattleItemMenu : MonoBehaviour looks at items in Inventory, and lets you call the generic Item.UseItem or something
Thank you i finally got it to work after hours of trying to figure it out by myself
UseItem might downcast to HealingItem, and then call Heal(pokemon, HealingItem)
but the SO does not carry code
There's actually nothing wrong with having code on a ScriptableObject
i mean the SO doesn’t have code specific to one .asset
You just have to call it yourself from somewhere
Right so - I'm really against the idea of ScriptableObject inheritance for the most part. It becomes completely unweidly to actually create the instances that way
the HealingItem doesn’t have a special function that checks Potion vs HighPotion to call different logic
You just need to really evaluate your options. Just like any inheritance pattern
apologies if this is the wrong category, how do i make the player go straight and not up?
inheritance in general is not great unless you put a lot of thought into it
SOs are no different
what does "straight and not up" mean and what does this screenshot have to do with it?
probably require even more thought tbh
btw I do have a different method, with an addon called TypeReferences, where I can tie a type to an SO, and the type can have code.
Can someone explain to me how exactly angularVelocity is defined with a vector 3? if I use (0,1,0) does it mean the object will rotate 1 degree on the Z axis every time it is called?
i mean literally the character go foward and not upwards when i press w
Well that would have to do with your code
also "forwards" may mean different things depending on your game style/camera angle, etc.
On the Y*
wdym by "every time it is called"? Angular velocity on a Rigidbody is expressed in degrees per second
So I have BuildingObjectBase, which might correspond to a ground tile, or a goomba, or ? block. Then I can give it a reference to the type GoombaBehaviour. This is a lighter version of using a Prefab, so you want to evaluate that option first.
short answer is - plug in "forward" as the direction to move in your code instead of "upward". I can't get more specific than that without seeing your code.
does all of this make sense?
first make a simple SO. Don’t fuck with inheritance until you have everything under control
remember you can only inherit once
but you can compose or implement many times
Guys, how can I make my camera not follow my player vertically when he jumps?
I am using cinemachine
Video for reference: https://www.youtube.com/watch?v=IH6G3yoE1bk
27s leaked gameplay video (Early Build) : https://www.reddit.com/r/Eldenring/comments/q9ibcs/reupload_of_the_27_second_gameplay_leak_youtube/
Okay okay, I did it, I made an ItemData : SO with a CreateAssetMenu. The ItemData carries Name, descr, model, sprite
Probably something that can be done from cinemachine itself
#🎥┃cinemachine
Then I made HealingItem which Inherits from that ItemData and it contains the public field healingAmount. and the method public Heal()
that’s a good start. Now make a simple Inventory (POCO)
Inventory should be a POCO because it is just a data structure to allow monobehaviours to edit and query inventory,
Inventory’s job is simple: Hold a bunch of items, and let us know what we have, how many etc
for that, you probably also want an Item (POCO)
the Item should mostly carry ItemData, plus any information that is volatile/transient/temporary. Like current quantity
or Favorite
Inventory should be able to take simple requests like: AddItem, CountItem, RemoveItem
And later FilterItems (to get all items satisfying a given criteria), but you can worry about that later
understand?
and do you understand why I’m setting it up like this?
i have one question i have score system in my game and i want the same score to be displayed in my gameover scene
so i know it has something to do with playerprefs but i dont know how to do it
What do you recommend for a beginner to learn physics at Unity?
don’t use PlayerPrefs. learn to use JSONs
what is JSON
look it up. and look up JSON utility
start with basic tutorials
every game uses basic physics. but if you are super new, you might want to start with Godot, as it grows
Okay yeah, I created the inventory to do what you said, It's a POCO which the methods to add remove count, and initialize the inventory in the start method. Although tbh I'm not too sure the reasons for POCO's aside from performance benefits and that it means it has no dependencies so it can easily be reused for other projects. I created an Item POCO with the field for ItemData : SO. It has a private field for amountOfItem.
I'm a development professional at Roblox Studio, but it's very different.
if something has no reason to be a monobehaviour, it should not be a monobehaviour
there are a lot of tutorials on the topic tbh. there’s just a ton
it’s such a big topic
the point of a monobehaviour is to attach it to a GameObject, and allow it to respond to messages, like Start, Update, OnEnable,…
curves are usually made with lerp?
try slerp
Inventory has no business being involved with any of that crap
also we will eventually want to Serialize it to save
but even without that point, it still should not be a monobehaviour
Huh ig I missed it, I'll watch a videos on it but for now I understand that it means that if something doesn't need to be attached as component then Mono is not needed.
I'm not sure how cooldowns are done in Unity
with a timer of some kind
you can use a Coroutine
this can be anything from a float variable to a yield instruction in a coroutine
yes. and you need to StartCoroutine on a MonoBehaviour
So now that I have these. How would I add the heal functionality to the HealItem which inherits from the ItemData : SO? Would I just make it a method public Heal() in the HealingItem script?
no
that is one part of making a coroutine, yes
actually, you could add Heal as a public method to HealingItem, which operates on a target
then different Monobehaviours can call this method at runtime
but be mindful to not edit the SO
editting the contents of the SO is bad
I might even make it public static Heal
does this make sense?
i cannot stress enough that you do not want the asset to change during runtime
Okay so I understand that I shouldn
if exactly how Heal works is the same across the whole game, and doesn’t require a lot of specific logic, you should make it a static member of the HealingItem class
t be messing the scriptableobject at runtime. But the reason why I dont understand this is because the way I've been doing my Heal functions is by refrencing the PlayerHealth script and running the Heal function using the argument for the amount. And as you know GetComponent is only available in Monobehaviours so I wouldnt be able to put that function on HealingItem which inherits from ItemData : SO. Btw im sorry for the trouble I dont know why I can't wrap my head around this
Hi everyone. I am a beginner at Visual Scripting, so this question is probably easy, but I can't find information online. I have received the task of creating a simple movement and power-up system in Visual Scripting. The large script makes my character jump; the other one is my trying to make a power-up to make my character jump extra high after it touches the power-up object. It does not need a set time; it just needs to jump higher after it feels the power-up every time you press the space key to jump. Can anyone help me, please? 🥺
no worries! & ur welcome 🙂
I just understood.. i fixed my issue after all these hours
i just had to write "_input.attack = false;" instead of changing the boolean, because the input.attack was true and it was constantly keeping the bool to true
what was issue?
and everytime i would put the boolean to false, it would instantly become true again
ohwait nvm you replied to that XD
You can GetComponent from anywhere
GetComponent is a method in gameobjects or components
You'd just pass whatever references you need in as parameters
if you have a reference to a component or GameObject, just call .GetComponent lol
Oh boy I forgot you could pass references as parameters, no wonder it never worked I just assumed GetComponent was a part of monobehavior. Thanks guys!
i would make Heal just take a reference to the Health component or whatever
or rather, it’s smarter to make a generic Status component, to hold any type of status for an entity. Including but not limited to health
!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.
@wintry quarry Well, this was a lot easier than I thought it would be, all this practice recently is paying off. Thank you for the idea. 🙂
public void AdjustScore(int scoreReceived)
{
playerScore += scoreReceived;
playerTextScore = playerScore.ToString();
for (int i = 0; i < playerTextScore.Length; i++)
{
MeshFilter meshFilter = scoreDigits[i].GetComponent<MeshFilter>();
MeshRenderer meshRenderer = scoreDigits[i].GetComponent<MeshRenderer>();
string digitValue = playerTextScore[i].ToString();
int indexValue = int.Parse(digitValue);
meshFilter.mesh = scoreMeshes[indexValue];
meshRenderer.material = scoreMaterial;
}
}
Nice
Fun fun fun 🙂
string digitValue = playerTextScore[i].ToString();
int indexValue = int.Parse(digitValue);
meshFilter.mesh = scoreMeshes[indexValue];
Why?
It works. lol.
converting an int to a string, then back to an int is good luck
So does
meshFilter.mesh = scoreMeshes[playerTextScore[i]];
you forgot to increment and decrement it
meshFilter.mesh = scoreMeshes[playerTextScore[i] - 1];
playerTextScore[i]--;
Now you are just being silly
silly would be using division
Honestly, can't tell if you're being seriously helpful or taking the piss.
taking a piss
He's taking the piss, I'm being helpful
Yeah I know you always are. 🙂
this wouldn't work the same though because playerTextScore is a string so playerTextScore[i] is a char which won't have the same value as it parsed to an int
playerTextScore is an array of ints
playerTextScore = playerScore.ToString();
string digitValue = playerTextScore[i].ToString();
that's indexing a string to get a char then converting that to a string
indeed. So
meshFilter.mesh = scoreMeshes[((int)playerTextScore[i])-48];
Is one better performance wise than the other or is the difference negligable? (genuinely asking. lol.)
he wants the char representation as an int, my bad
you may want to subtract '0' from that unless the values are supposed to be like 48 off
Hmm? Not sure what you mean. I was getting weird high numbers earlier while I was figuring it out, but now the scores are representing correctly etc.
steve is implying that you can just cast the char to an int instead of parsing it like you're doing. but '0' == 48 whereas int.parse('0') == 0
Ah I see. Well tbh, this works, so I'm happy with it. lol.
But honestly thank you for the input. It is very much appreciated. 🙂
honestly though you're creating a bunch of garbage unnecessarily. when you can just use the actual score value before converting it to a string and get the individual digits from that fairly easily
i have a bug where my code randomly stops working and forces me to restart the editor
works fine normally but sometimes it just randomly stops working
infinite loop
wouldnt the code always fail when i press play every time in that case?
no, unless unity has somehow solved the halting problem
an infinite loop will cause the editor to freeze because it is stuck in the loop and cannot proceed to the next frame
no the editor doesnt freeze
then what do you mean by "my code randomly stops working and forces me to restart the editor"
sometimes the script just wont run when i press play, but most of the time it runs
then the script wont run when i press play again
however when i restart the editor the script works fine for a while
and by "won't run" you mean . . .?
until it randomly stops running after a while
its a gun script, i cant shoot and it wont show me anything in the debug.log
it normally does
restarting the editor solves the issue temoporarily
oh you know what, i see you subscribing to some static events but not unsubscribing them. have you turned off domain reload without understanding what that does?
do you have to unsubscribe to them?
yes
yea
does the script fail after a while otherwise?
especially if you have turned off domain reload because then you're not cleaning up your static event so it will keep the same subscriptions even after restarting play mode. so you'll end up with some null reference exceptions and the like preventing the newer subscribers from reacting to the events
!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.
public void AdjustScore(int scoreReceived)
{
playerScore += scoreReceived;
playerTextScore = playerScore.ToString();
for (int i = 0; i < playerTextScore.Length; i++)
{
MeshFilter meshFilter = scoreDigits[i].GetComponent<MeshFilter>();
MeshRenderer meshRenderer = scoreDigits[i].GetComponent<MeshRenderer>();
meshRenderer.material = scoreMaterial;
meshFilter.mesh = scoreMeshes[((int)playerTextScore[i]) - 48];
}
}
Better? 🙂
where do i find domain reloading
oops, forgot to remove a line 😛
or just clean it up on Destroy
https://docs.unity3d.com/Manual/ConfigurableEnterPlayMode.html
you should still be unsubscribing from static events in OnDestroy or OnDisable though
yes, much prettier
i have no clue what domain reloading is though or if ive disabled it or not
okay so check the link i just gave you
Hehe, thanks for the input 🙂
and it is perfectly fine to have domain reloading off, you just need to make sure you are properly resetting your static variables
through destroying them?
if you like waiting a long ass time to get into playmode
just cleanup like they've suggested
OnDestroy for example will run when scene is cleaning
so all i have to do is shove it into my script?
-= is the opposite
so yea
afaik its good practice to cleanup your subscribes regardless,
add the whole static not resetting in unity with DR off
im using OverlapBoxAll and im working if i target every layer expect one
put that layer in ~mylayertoignore in the overlapbox
Hmm, weird issue. Probably being an idiot.....
indicatorWater.material.SetFloat("FillLevel", playerWater/100f);
Can anyone see why this isn't adjusting the 'FillLevel' of my shader? It's exposed etc. (indicatorWater is the meshRenderer of the object)
This works fine, so it's obviously something I'm doing wrong in terms of the material grabbing.
imgWater.rectTransform.localScale = new Vector3(1, playerWater / 100, 1);
is playerWater an int or float?
you might have written an infinite loop in your code
imma check thx
It's a float
got it haha thanks mate ❤️
so what's wrong with it exactly?
The FillLevel float on the materials Shader (shadergraph) isn't getting updated as it should.
how do you know?
playerWater is being updated and I 'run out' and the value in the inspector doesn't change
How are you verifying that it's being updated or not
in the inspector for what?
The material?
Doing indicatorWater.material creates a new material, if you aren't aware
specific to that particular renderer
OH! Really?
yes - use .sharedMaterial if you want the "original" material
Aaaah, that would be the issue then. lol.
Right, gotcha, thank you 🙂
Hmm. Or not. Still not doing what it supposed to be doing 😕
This is the whole method....
public void AdjustWater(float waterUsed)
{
playerWater -= waterUsed;
if (playerWater > 0) {
//imgWater.rectTransform.localScale = new Vector3(1, playerWater / 100, 1);
indicatorWater.sharedMaterial.SetFloat("FillLevel", playerWater/100f);
}
else
{
playerWater = 0;
indicatorWater.sharedMaterial.SetFloat("FillLevel", 0f);
//imgWater.rectTransform.localScale = new Vector3(0, 0, 0);
}
}
This lives on a singleton that I'm using as a Game Manager (not sure if that would be relevant)
Oh wait, I just remembered something........
Yep, was being an idiot. Been spending lots of time with VFX graph and forgot that with ShaderGraph you need to use the Reference and not the name. Sorry.
Hey, what are the solutions to changing font size with in game settings?
Do you have to change font size for all gui elements separately?(that sounds wrong)
whats with One Piece everywhere fr lol
The one piece is real
I had this avatar for many years, so idk
Thanks
Font size of the font asset might be what you want
how to get the child's from object's?
GetChild
Through the Transform component
transform.GetChild(n)
foreach (Transform child in transform)
transform.Find("ChildName")
transform of parent object?
i have a problem where i cant display my score in the game over screen
yes
ok
why not? What is stopping you?
i dont know how i have wathched many videos and read forums but i cant seem to understand it
what's going wrong though?
You need to be specific
what part isn't working?
is there an error?
Something stopping you when trying to set things up?
You need to understand what's not working to fix what's not working.
But what if I want to grab children from a TextMeshPro object?
Assuming constant latency, shouldn't this give me the number of ticks of latency? (Tick rate = 64)
Everything is a GameObject. TextMeshPro is just a component on it
Every component can access the Transform
i made debug and it says that it reads the playerpref but i dont know how can i attach the data from that playerpref to a text
No you can't Implicitly convert it
you have to access the Transform
through .transform
.text =
You aren't trying to convert, it's a whole separate component
if you have a terrain which had width: 199 and height: 99 and you scaled it by a factor of 500 which would give you width: 99,500 and height: 49500, What would be 1 meter now be in the terrain, would it now be 500?
I'm trying to profile my build and I keep getting that this is what takes the longest. What is it?
Waiting for the GPU to render the scene
I see
Then how can I profile a shader so that I know which instructions are taking so much time? I made a custom terrain shader and is taking around 6ms to run (which doesn't make much sense since it's quite simple)
How can I make use of it to profile? I don't see speed of instructions
Yeah, I want to make it more efficient, but I don't know what is not efficient from it
Actually debugging or profiling a shader itself is beyond my ken. check in #archived-shaders
Okay
sup, i have a parent class, with two children classes (ships, and planes) All 3 share the public function UpdateTooltip()
theres some code in the base version, and then the children classes override it, but call the original within their implementation as well.
What i'd like is to be able to call the 'youngest' version of this. What I mean by this is without knowing whether it's a ship or a plane, I want to call the UpdateTooltip function with the full implementation rather than just base.
I was thinking this could have something to do with abstraction or interfaces, but I'm not that experienced with them so I thought I'd ask
I'm making a football runner for one of my Udemy courses. I want when my player collides with the "out of bounds" box collider to freeze all rigidbody constraints. I'm able to FreezeAll but i have two issues.
- when the FreezeAll line of code runs, the out of bounds colliders no longer stop my player.
and 2. The constraints are all checked frozen, but my player still moves.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
If you call UpdateTooltip on something declared as the parent class, but is actually the child class, it will call the child classes method
It just comes down to what the instance actually has
GetComponent<Vehicle(OrWhatever)>().UpdateTooltip()
Will call a plane's method if the vehicle is a plane
You can also do this with an abstract class or an interface
hey guys that doesnt work? tu turn true and false? ```cs
void Update()
{
PlayerMovement();
if (Input.GetMouseButtonDown(0) && canShoot){
shouldShoot = !shouldShoot;
Debug.Log("shoud shoot:" + shouldShoot);
if (shouldShoot){
InvokeRepeating("Shoot", 0f, fireRate);
shouldShoot = false;
}else{
CancelInvoke("Shoot");
}
}
```
basically ur setting should shoot always to false and then ur checking if its true
then it wont invoke
{
PlayerMovement();
if (Input.GetMouseButtonDown(1) && shouldShoot == false){
shouldShoot = true;
}else if (Input.GetMouseButtonDown(1) && shouldShoot == true){
shouldShoot = false;
}
if (Input.GetMouseButtonDown(0) && canShoot && shouldShoot == true){
if (shouldShoot){
InvokeRepeating("Shoot", 0f, fireRate);
}else{
CancelInvoke("Shoot");
}
}
}```
tryuinmg to test here
!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 want basically to click one time the mouse and keep shooting
GetMouseButtonDown is already only called once. Just invoke your method there. No need for all those if bool checks.
Then you can cancel it on GetMouseButtonUp.
that would get rid of the point of clicking one time
like aon and off auto shoot
click one time, stay there shooting until i click again
you can use a bool for that
Hey, what's the difference between Handles.PositionHandle() and Handles.DoPositionHandle() ?
public static Vector3 PositionHandle(Vector3 position, Quaternion rotation)
{
return DoPositionHandle(position, rotation);
}
```Actually never mind, it seems the former will call the latter 
Yeah not sure if DoPositionHandle is even supposed to be exposed lol
Seems like an old feature that Unity forgot about (?) and didn't clean it up
Probably. The Editor API is not as clean as the game API
hello does anyone know what this is? the character was originally at that spot for context
Does the character have a parent object?
Maybe some component on it. Kinda looks like a wheel collider but maybe not
the circle only shows up when i click on armature
when i click geometry/skeleton it disapear
yeah its the rig
Also it looks like you moved the child object, you probably want to move the parent instead
but the code is in the armature, wouldn't the child also move?
Child moves with the parent, so move the parent, otherwise their positions will not match
I mean it looks like the child's local position is not zero. Assuming that the selected object in this screenshot is the child
This will result in a weird offset
Or is the selected object the parent?
in this picture i selected the armature(parent), this photo is after i move the character in play mode but that white circle still stands there unaffected with the moving
in edit mode, the white ring doesn't appear i think
Ah okay then. You can check the Gizmos menu and disable specific gizmos to see what is drawing it
Looks like it's the rig though, at least if you are using the animation rigging package
Okay 👍 , thank you very much for the help
is there something i can use instead of OnCollisionEnter so its when the object goes into the object but not necessarily collide with it
Trigger colliders and OnTriggerEnter?
ok now idk how this channel works but if i send a snippet of code could you assist me switch it from collision to trigger
cuz i have a thing here that i used for something else and im trying to like repurpose it cuz i have no idea how to do it from scratch
!code
Use what the bot says
📃 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 longer than like 5 lines use a paste site
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "GameController")
{
this.gameObject.GetComponent<Renderer>().material.color = new Color(0, 255, 0);
}
}
this is all it is so i dont think i need a paste site
So change OnCollision to OnTrigger
The Collision changes to Collider in the parameter
And collider can skip the gameObject part
collider.tag
And
collider.GetComponent
Also, I recommend CompareTag("GameController")
Over
.tag ==
That is it
so collider.CompareTag you mean? or where do i put the CompareTag
Oh no, one more thing,
Color takes between 0 and 1.
In this case it won't make a difference, but it will if you didn't have the max value
Yes.
The place where you check the tag
Written exactly how you say
ok so
private void OnTriggerEnter(Collider collider)
{
if (collider.CompareTag("GameController")
{
this.gameObject.GetComponent<Renderer>().material.color = new Color(0, 255, 0);
}
}
should it look more like this now?
Yeah, looks right.
You also need one of the colliders to be set to trigger now, of course
And color still has 255 instead of 1
No big deal, like I said it doesn't actually matter here hahaha
It just takes it as "over the max value" and uses 1 anyway
yeah
its a vr hand lol
im just tryna make it so when i hit a box with my hand it doesnt actually have to collide it can go through and still activate the thing yknow
its not working but theres no errors so ill troubleshoot somehow
OnTrigger needs a rigidbody
Is there a rigidbody on either the hand or on what you want to touch?
Not sure how that works in vr
ill put a rigidbody on the thing im tryna touch first cuz that would work better if it does work
yep it works now thanks lol
just had to add a rigidbody to the cube
ok i have one unrelated question now that has nothing to do with vr
idk why i cant figure this out for the life of me hold on
i have a public int called money and whenever i do this one thing it goes up by one
how can i call the public integer in a different script???
Gotta get a reference to the object and get the script from that
Then just use dot notation to get the variable (or better yet, call a method)
ima be real i been looking at this for like 10 minutes and i have NO idea what to do 😭 im so tired rn
I can suggest something more if you give me more info. What object is the integer holding script on?
What object do you want to get the integer from?
Are either of the objects instantiated?
ok so the object thats holding the script is the Target im trying to throw an object at, the object im trying to get it from is the box i just made green as a test, neither are instantiated
my goal is to on the box check if the integer is at a certain amount, then remove that amount from the integer and do something
Can I not pass a Vec3 into a Vec4 constructor?
Isn't that what this is? (from Vector4 class)
how do I create multiple instances of a sprite?
with Instantiate()
will they auto delete if it hits?
instantiate doesnt auto delete stuff if thats what you mean
you have to put in a quick line after im pretty sure thats what i do
If they aren't instantiated, drag the script into a field. In the link I gave, this is called a serialized reference
im using
[SerializeField] private Transform _target as an example
and im trying to change it to what i want so would it be
[SerializeField] private int Money;
?
You would want the thoe to be the script class name
the thoe?
the _target one?
the script class name of where im trying to take it from or where im trying it put it
i gotta go to sleep now but ill try again tommorow 🙏
Oh hahaha. I meant Type! Sorry
A type typo
So like public ScriptOnBox script
Then
script.Money;
how do I make it so that a sprite has a rigid body?
Explain what you are trying to do 😄
You can use a Sprite in 3D, it more or less uses a plane. I think they hid it behind the
2D in package manager in 2021 or so.
But yeah, you can add a sprite. Apply a box collider. Then apply a rigidbody.
sprites are just assets, not game world objects
You can use a SpriteRenderer
i am trying to render a sprite
It would be really convenient if there was a component called Sprite Renderer then wouldn't there
i have this attribute for my editor tool script:
[MenuItem("Tools/Asset Database")]
but its not showing in unity
do you have any compile errors?
i added it with the sprite renderer it still won't show up
Show your whole method + attribute
is it in view of the camera?
What are the positons of the objects?
Z position
//base class:
//public abstract class DatabaseTool<T> : EditorWindow where T : Object
public sealed class AssetDatabaseTool : DatabaseTool<TestAsset>
{
[MenuItem("Tools/Asset Database")]
public static void Init()
{
var window = GetWindow<AssetDatabaseTool>();
window.titleContent = new GUIContent("Asset Database");
window.Show();
}
... regular code
Not 100% sure, but move it to an Editor folder
it is in editor folder
ah, the z position had to be 0
it has to just be in front of the camera.
Not equal or behind it
or within its near clip plane distance
i edited the code to show the base class definition
it inherits from editor window so it should work
i must be misunderstanding how the attribute works
very confused
https://img.sidia.net/ZEyI5/hexiFomU81.mp4/raw
Nah your usage is right
Can you make your class derived from a base generic editor window class
wondering if the inheritance is what's breaking it ?
yeah it shouldn't but right now it should be showing a menu 😛
public class PowerupDataEditor : OdinMenuEditorWindow
{
private string _defaultPath = "Assets/InfinityShooter/Powerup/Powerups";
[MenuItem("Tools/Sidia/Powerup Data")]
public static void OpenWindow()
{
GetWindow<PowerupDataEditor>().Show();
}
[...]
this is also working for me
100% no errors
show top right of console?
i wonder if i have two editor tools with the same menu item directory and thats broken it some how
try a different path for testing sake?
how do I assign a prefab?
To what?
typically by making a serialized field and dragging+dropping it in
I have this code right now that creates a single brick, how do I create multiple?
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D))]
public class Brick : MonoBehaviour
{
public int points = 100;
public bool unbreakable;
private void Start()
{
ResetBrick();
}
public void ResetBrick()
{
gameObject.SetActive(true);
}
private void Hit()
{
if (unbreakable) {
return;
}
// Destroy the brick immediately
Destroy(gameObject);
GameManager.Instance.OnBrickHit(this);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name == "Ball") {
Hit();
}
}
}
A field? Make a field with the [SerializeField] attribute and use the type of the component that the prefab has
this code doesn't create a brick. This code is a brick
if you want to spawn bricks in the game, you will need a script to do that, yes
You can certainly call it "BrickManager" if you wish. "BrickSpawner" might be more appropriate
alright
i have to create a new empty gameobject right
for what
Yeah, probably. For the spawner
Unless you have a manager type object somewhere already and want it on that.
Really up to you
to attach the brickspawner to
Just don't attach it to the brick object 😄
surprisingly common error
what would this script look like?
that's entirely up to you
holds a variable for the prefab
has some condition for when to spawn
calls instantiate on the prefab
at some point it will need to call Instantiate to spawn a brick
but the how, when, where, and why of spawning bricks is up to you
The referenced script is missing 🤷♂️
Can happen if you rename it outside of unity or your IDE
Or with compile errors
ah, got it
using UnityEngine;
public class BrickSpawner : MonoBehaviour
{
public GameObject brickPrefab; // Reference to your BlackHoles prefab
public int numberOfBricks = 5;
void Start()
{
for (int i = 0; i < numberOfBricks; i++)
{
GameObject newBrick = Instantiate(brickPrefab, GetRandomPosition(), Quaternion.identity);
}
}
Vector3 GetRandomPosition()
{
float x = Random.Range(-50f, 50f);
float y = Random.Range(-50f, 50f);
return new Vector3(x, y, 0f);
}
}```
what do I put for the brickPrefab?
do I drag the sprite image of the brick to this:
@summer stump
The object with the brick script on it
Naming is personal. Whatever you choose is gonna be best for you (within some limits haha). But that one is fine
I think your issue is here:
private void Hit()
{
if (unbreakable) {
return;
}
// Destroy the brick immediately
Destroy(gameObject);
GameManager.Instance.OnBrickHit(this);
}
you destroy it, THEN pass it to the gamemanager
OHHHH
It should last for the frame until that call 🤷♂️ but I dunno
i first pass then destroy?
Worth a shot. That is the most obvious related thing I see
If it's not that, then I'm unsure haha
yeah that was it lol
Nice
Hmm. Destroy happens at the end of the frame though 🤔
Oh it might actually be different because this is in the physics loop. Idk I probably have to do some testing
Right?
I threw it out there just cause I saw nothing else obvious
I guess we learned about another Unity quirk today
I use Destroy last anyway though, or just return right after it
did you confirm that?
Im not on my PC until tomorrow
So I should add, another potential quirk
I would imagine that it wouldve happened to me at some point though
Maybe it did but my brain RAM is full
itt's not a quirk, it's an error
I need to see OnBrickHit.
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D))]
public class Brick : MonoBehaviour
{
public int points = 100;
public bool unbreakable;
private void Start()
{
ResetBrick();
}
public void ResetBrick()
{
gameObject.SetActive(true);
}
private void Hit()
{
if (unbreakable) {
return;
}
GameManager.Instance.OnBrickHit(this);
// Destroy the brick immediately
Destroy(gameObject);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name == "Ball") {
Hit();
}
}
}
this is not OnBrickHit
using UnityEngine;
public class BrickSpawner : MonoBehaviour
{
public GameObject brickPrefab;
public int numberOfBricks = 5;
void Start()
{
for (int i = 0; i < numberOfBricks; i++)
{
GameObject newBrick = Instantiate(brickPrefab, GetRandomPosition(), Quaternion.identity);
}
}
Vector3 GetRandomPosition()
{
float x = Random.Range(-5f, 5f);
float y = Random.Range(-5f, 5f);
return new Vector3(x, y, 0f);
}
}```
Oh.
this wouldn't cause an error even if you destroyed the game object the brick was on
LoadLevel causes it to destroy in the middle of the method or what?
and where does that error come from?
LoadScene doesn't do anything until the next frame
show GameManager.Cleared
I just assumed that the error came from the previous code. I shouldn't assume
that would also not cause an exception
so we're good now?
You can access fields on a destroyed Unity object without causing an error.
no. you are keeping the destroyed objects in your bricks array/list
You get an error when you try to use something that Unity provides
like accessing gameObject
Don't destroy the brick. Deactivate it.
how do I do that?
so don't do this
yes, because brick isn't a game object
ah
so you can't make it inactive
i see
you already know how to get the game object for the brick
yep got it
I see an unconfigured VSCode
unfortunately yes
Fortunately you can (try to) configure it or just switch to Visual Studio Community
if I made a function from private to public can I access it from another class?
ill try something for that
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class Ball : MonoBehaviour
{
private Rigidbody2D rb;
public float speed = 10f;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
private void Start()
{
ResetBall();
}
public void ResetBall()
{
rb.velocity = Vector2.zero;
transform.position = Vector2.zero;
CancelInvoke();
Invoke(nameof(SetRandomTrajectory), 1f);
}
private void SetRandomTrajectory()
{
Vector2 force = new Vector2();
force.x = Random.Range(-1f, 1f);
force.y = -1f;
rb.AddForce(force.normalized * speed, ForceMode2D.Impulse);
}
private void FixedUpdate()
{
rb.velocity = rb.velocity.normalized * speed;
}
}
i want to use the random trajectory for the bricks
Generally speaking, yes
It is very easy.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
follow the instructions for VS Code
i'll try that
It can be difficult when you try to take creative liberties with the instructions
so, don't skip any of the steps, and read them carefully
Not for all unity versions. I struggled to update to the new vscode integration on an early 2021 unity version
But if you got LTS then it is probably easy
The editor defaults to including the "Engineering" feature, which locks you onto an old version of the Visual Studio Editor package
which is fantastic.
i see no reason for these "features" to exist
Can you elaborate?
how would I use randomTrajectory in the brick class?
these fellas
If one is installed, it locks the packages it uses
clicking "unlock" does literally nothing, which is very goofy
you have to remove the entire Feature (uninstalling all of its packages), then install what you want
🫠I dont think I even have that feature in my package manager. I havent't felt like upgrading in ages since my Unity is stable @swift crag
you only see Features when you're viewing the "unity registry" list
Yeah, I've learned to just say remove that package when anyone is having issues with vs code configuration, without even asking to see. It is OFTEN a culprit
well, it's definitely a culprit
Just add it as a component to the prefab
I just checked the docs and it was added in 2021.2, I am on 2021.1
because it forbids you from installing a new enough version of the Visual Studio Editor package
You attach it to the prefab
ah, that'll do it
Also, I went and tested if anything funny happens when an object is destroyed in FixedUpdate rather than Update
just for kicks
I don't see anything weird. Although, I was slightly surprised the object was destroyed at the end of the fixed update cycle
So destroyed just before Update?
can I just do this?
I would suggest doing it on the prefab.
I guess the term "frame" in the docs applies to physics frames and rendering frames accordingly
I guess but it's silly. The whole point of prefabs is to avoid having to do this
You might as well set up as much as you can in advance.
i tried that tho, it still doesn't have the rigidbody
Show the inspector for the prefab.
Actually docs explicitly mention the Update loop 🤔
you've attached it to the brick spawner
That's the spawner
the empty gameobject is my prefab
No
It's not
That's not a prefab at all
in fact, there are no prefabs in this image
you can instnatiate any unity object
you're instantiating copies of the BlackHole object in your scene
the brick spawner is attached to this brick prefab
I sent you the link earlier for how to work with prefabs. I recommend you read it
i did, that is how I got the spawner working
That's both incorrect and nonsensical and a really bad idea all in one
You're spawning spawners
oh
you should have a spawner whose job is to create copies of a brick prefab
Actually looks like you're spawning "Black hole"s
yeah
the brick prefab shouldn't exist in the scene at all
Yeah, this seems like another case of docs being wrong
it's a prefab.
i was too lazy to change everything from bricks to blackholes for variables
the meaning of "Update loop" could be stretched a little I guess
Anyway you seem to have skipped the whole "create a prefab and reference it" part
(Fixed)Update
Update being capitalized in the doc really adds to the confusion tbh
suppose I asked you to run a 100 meter dash
i added a rigid body to the black hole script, now it isn't complaining
would you decide you're too lazy to put shoes on?
and then fall over and hurt yourself
that sounds really inefficient to me
should I rename everything then?
slow down and pay attention
☝️ You still don't have any prefabs in your game.
can you explain what I did then?
you're just referencing another object in the scene
there is no reason you can't do that. obviously, it works
yes
but what if that particular object gets destroyed?
it's just like any other object in your scene
now you can't spawn any more copies
a prefab is an asset
it doesn't exist in a specific scene
but you can reference it, and create copies of it
hm ok
it's a template
so should I delete what I have right now?
not quite
Set up the object the way you like it
then drag it from the hierarchy into the project window
bam, prefab
Just turn it into a prefab
and go read that page Praetor send again
do I remove the brick prefab here?
Don't forget to then delete the one from the scene
That isn't a prefab
well do I delete it then?
After creating a prefab.
There's nothing even called brick there
I'm still very confused by these names, yes
you have a "black hole" being spawned by a brick spawner
ok hold on, let me rename everything
since i only called it brick because the tutorial did that
there are only two hard problems in computer science, and we aren't doing cache invalidation
naming things is the other hard problem
might as well not make it harder
I'm re-discovering how I engineered some stuff in code I wrote eight months ago
My names are a little bit vague and it's tripping me up
I have Item and InventoryItem and they're unrelated concepts
actually I think Item might be dead code...
😵💫
Simply drag the object you want to BE a prefab into the Assets folder. It will turn blue. Then you drag the PREFAB from the assets folder into the field
Don't drag the object from the Hierarchy, because that is an actual instance of an object that can be changed and destroyed and render your reference useless
in short: things in the hierarchy are real objects in your scene
you should reference those if you care about the specific object
in this case, you do not care about the specific object
you just want the template.
hello i need help with my code, been trying to make a gameobject inactive when the player has interacted with enough npcs, its using a debug statement as a placeholder, but it never shows up on the console for some reason
well, who calls IncrementCompletedNPCS?
and do you have any proof that it's being called?
currently you only log if that condition is met
theres a seperate script for npcs that calls it whenver the interaction with them is done
prove it by logging something at the very top of IncrementCompletedNPCS
maybe along with the current values of the counters
I recommend this debug.
Which will also tell you if the value is being reset somehow
$, not % !
i added a line to check https://gdl.space/eradomiquk.cs but it also not does not show on console
You might just have the console filtered.
I have info and warning messages off
(my mouse is hovering over the info toggle, so it's kind of half-lit-up)
just to add, the counter goes up in the inspector
then you definitely have the console filtered
oh yeah found it ty
You're trying to use a variable that doesn't exist
Also your IDE is not configured
still havent done that, low on time right now
why wont it exist?
Otherwise it would be underlining in red
You never created it
Low on time is a good reason to configure it. You're wasting precious time on silly errors because it's not configured
justt found it
It can take as little as 5 minutes
You cannot use something that doesn't exist. You need to configure your ide to get help on this server.
you're going to be REALLY low on time if you keep trying to work with broken tools
quit being penny wise and pound foolish. fix your code editor.
Just to hammer what Dalphat said home..
when I went to make that little test case earlier, I first configured my code editor
and that was for a throwaway project I've already deleted
Follow the instructions.
i did
the unity extension was downloaded
Okay, that is the correct VSCode extension to install, yes.
Now follow the rest of the instructions.
follow up on my question earlier, the console is showing the correct debug statements but the gameobject i want to set inactive isnt
https://gdl.space/yerefipufe.cs
Are you getting a nullrefexception?
no
isnt becoming deactivated*
Hmm ok. You get the log, but it isn't being deactivated it.
Do you set it active anywhere else?
it becomes active when an npc interaction ends, but i dont think it continously keeps it active?
Errors should now be highlighted, and names should be getting auto-completed
Maybe log the active state right after deactivating it?
then log wherever you activate it?
Not sure
Or just put breakpoints
why can't i assign this:
blackholes = FindObjectOfType<Blackhole>();
to this:
private Blackhole[] blackholes;
it worked when the variables were called brick
Because FindObjectOfType returns a single Blackhole, and Blackhole[] is an array
There is FindObjectsOfType though
(note the s)
similarly, if i make some other gameobject active, it works
wdym field?
the overworld canvas is currently active, once i interact with 4 npcs, the overworld canvas should become inactive but its not
the placeholder becomes active though
how would you guys loop through the game objects in the array?
Google c# loop
but how would I get every combination?
what do you mean combination? Like you want multiple gameobjects?
a loop inside a loop
i think i have to apply the Fg = (G * m1 * m2) / r^2 formula between every game object
right?
Then this is not loop, it is backtracking, basically:
Void dfs(int idx){
If idx>=length return
take this, dfs(idx+1)
Skip this, dfs(idx+1)
}
Typing in phone is painful
ill try that, do you think i should make a class called force calculator?
or just do it in a function
im not sure how to plan this
An algorithm has nothing to do with class
But making a struck will make your life easier since you can load the data you need as struct properties no need to pass it in next function call to dfs
private struct solution{
Properties
Constructor()//or driver
Run()//returns the result
Other helper methods
}
hello, why do unity and visual studio said this project had compiler error even though the script existed?
BuildManager doesn't exist it said. But it exist in the file.
There are no compiler error in my coworkers' PC, but only here. Why?
Try reimport it
trying to add a mesh to my asset as a subasset in the asset database but i get the error:
Couldn't add object to asset file because the Mesh is already an asset doesn't really make sense because its just a mesh instance but not saved to the asset database am i missing something to get tihs to work
hello, once again i need help with my event script
https://hatebin.com/qujocbmhah
Can someone look at it and tell me how i can make the events occur at random years, currently they just occur as soon as they can, and they completely ignore their odds even if it is set to 0.0001 they occur as soon as possible one after one
im assuming youre replying to me
can you be more specific pls on what i need to change
I am on my phone and i maybe overlook the code, but i cant see some codes like: if some random value>odd then active event in trigger event
They aren't telling you what to change. They are asking where to look. It's a lot of code, and nothing (to me) jumps out as probability checking
do i use a character controller or rigidbody if im controlling a ragdoll
For physics based stuff you use rigidbodies
alright
Is your character a moving ragdoll (known as active ragdoll), or do they ragdoll under certain conditions?
If it is not an active ragdoll, it does not matter which you choose because your movement would be independent of the ragdoll
it's an active ragdoll. I have a problem connecting the rigidbody of the root gameobject to the child colliders, since the child colliders are not linked to the root rigidbody because they are already connected to the joint's rigidbody
Each body part is gonna need a configurable joint and a rigidbody. The configurable joint connects the current part to another body part (arms to chest, chest to hips, etc)
Im not sure what you mean in your last sentence tbh
its all setup, but i have a hard time controlling it with buttons/keys
i tried using a rigidbody at the root gameobject but it starts behaving weirdly.
the character ignores other colliders and just phazes through like it's a trigger
This isnt 1 rigidbody you would need, you need like 10+. One for each body part.
Typically I saw people use the hips of the ragdoll to move it, as that's the center of mass. So you would apply any velocity changes to that rb. If you're object is going through other colliders then you're likely not moving in a way which respects physics even
Making an active ragdoll as a player is honestly very hard, I'd recommend experimenting more with unity before doing this.
yh i already set that up. i just found it hard to move the character as a ragdoll. it was easy to move the character when it wasnt a ragdoll
its my first time using ragdolls, so i will stick to changing the character to a ragdoll when necessary method since u mentioned it in one of your earlier messages
That was me asking what you were doing specifically. If your entire game concept is revolving around active ragdolls then itll have to be one the whole time
Itll just be a lot of experimenting to fine tune values like how much force the limbs should apply to reach their desired rotation. Then you'll probably add more like grabbing and other physics based interactions. It is a lot in comparison to a normal character
If you just want something that ragdolls on death then it's a lot simpler. You just toggle all the rigidbodies/colliders for the ragdoll, without worrying about it needing to stand
that sounds like a better idea. ill do that instead
Hey guys, instead of doing like that to invoke the boss the times I want, is there a better way to do this?
Why the invokebossone is invoked in 240 and 20 seconds later it is invoked again
Btw use coroutine or timer
i miss tiped the 240..260.. but ok will try ty
Hi guys. I just learned about the singleton pattern. What are the most common design patterns when developing games ? Are there any patterns that i have to know about other than the singleton
State machines, events, dependency injection. Stuff like that.
Maybe SOLID principles
What's neat.
void Start()
{
StartCoroutine(SpawnerCoroutine());
}
IEnumerator SpawnerCoroutine()
{
int spawnerTime = 120;
int spawned = 0;
while(spawned++ != 16)
{
InvokeBossOne();
yield new WaitForSeconds(spawnerTime);
spawnerTime += (20 * (spawned < 3 ? 20 : 60));
}
}
Have fun
spawnerTime should not be increased, just assignment
I don't know what you're talking about
+= to =, otherwise the spawner time just keep increasing
Indeed, so the code is correct
This code changes the spawnerTime to 140, then 160, then 220, then 280
The only mistake I made here is that the initial question actually changes from 120 to 240, so the first increase should have an extra 100
But this code should not be taken too literally to begin with
They're only those values in the original code because they're all invoked at the same time. In a coroutine you don't need the timer to increase in the same way, just be the correct value for between each spawn
Oooh, you're correct, they should be assigned rather than incremented. My mistake
If i have an animator and ive replaced it with an animator controller override. And i wanna do animator.Play(clip); what do i put in there? The overwriter clip name or the original clip name?
Just need some help with some (basic?) maths.
So on my character controller the rotation of my Camera and Player are different but I want the rotation of my player to depend on movement keys + camera rotation.
character.forward = Vector3.Slerp(character.forward, moveDir, Time.deltaTime * rotateSpeed);```So how can I adjust this to take into account my camera rotation? I assume I multiple moveDir by some normalised value of camera rotation?
moveDir is just a vector2 of (X, Z)
Or maybe some use of the camera.forward? 
If I multiply moveDir using the camera, it only works when moving diagonally
So if I hold "W" and "D" the character faces the same direction of the camera regardless of direction but if I hold 1 direction by itself it changes nothing and just always uses world position
Ahh I'm stupid... I need to use the camera.right for the "x" that's why it only works with 1?
🙂 Sorted
if i do this.variable = variable; are there noob traps?
instead of something like variable = _variable
no that's fine
ok, thank you. In every tutorial a watched no one did this, they all did either variable = _variable or variable = variableNew
its all right but personally prefer give different names to arg because in future when you revisit code , then you easily read it
Can someone explain what this highlighted code does?
It declares a list variable, creates a list object, and assigns the variable to refer to that object
the assigning is to ContactPoint2D right
No? It's to a list that can hold ContactPoint2Ds
what is it referring to?
"ssigns the variable to refer to that object"
what object?
The list
is it a list that already exists?
or is it just a list that holds a value or type ContactPoints2D
No, the list is created by new()
It is a list that can only hold ContactPoint2Ds
It's the same as new List<ContactPoint2D>()
II see
how do I make it so that it will automatically play the fade out after fade in? when I triggered the fade in in the code it won't play the fade out
But check has exit time and set at what point of the animation it should transition
FYI, private set; can be removed on the properties if you don't plan on modifying the value any more
but then i can modify it from everywhere?
No, if your property only has a getter and not a setter, this indicates it can only be assigned a value through the constructor
You're confusing it with having both a public getter and a setter
There's also init; but this is not supported in Unity I believe. The use case is quite niche, though
oh, i will try it, thank you!
is there a way to start a coroutine from another script? I tried this gameObject.TryGetComponent<pickupweapon>(out pickupweapon PickupScript); StartCoroutine(PickupScript.ChangeValues()); but got this error 'pickupweapon.ChangeValues()' is inaccessible due to its protection level
is it public?
no it isnt thanks
Might want to go over some some C# basics. Specifically access modifiers.
I didnt know that we can put public or private before IEnumerator
IEnumerator is just a return type of the method.
it's possible but it's not good practice
best practice is for a script to run all of its own coroutines
e.g. instead of doing StartCoroutine(PickupScript.ChangeValues());, you should do PickupScript.BeginChangingValues(); where BeginChangingValues is a function that starts the ChangeValues script internally from that script
e.g.
public void BeginChangingValues() {
StartCoroutine(ChangeValues());
}```
this ensures that the ChangeValues coroutine's life cycle is tied to the script that owns it, rather than some other random script/object
https://gyazo.com/d50b22dc938224be4f736d43469f1b9c
Anyone able to help me understand why my 'Player' transform doesn't change?
The character controller part does
Trying to make a checkpoint kind of system but I think it's bugging out because of this
because ur moving the child not the parent
child don't move parents
please advice couse for c# unity
Hi guys ! I want to use an AddListenerEvent on my toggle but only if the toggle became True and not on true to false. I did something like that but it didnt work :
myToggle.onValueChanged.AddListener((on) => {MyFunction();});
You need to use an if statement to check
Hey! anyone here worked with microsoft's mesh toolkit before ?
myToggle.onValueChanged.AddListener((on) => {
if (on) {
MyFunction();
}
});``` @normal arrow
Thank's man ! didn't know i could do it like that ! it works perfectly
check the pins in this channel
plz advice udemy couse
I've made some cylinders and squashed them down a bit to be rotating circular floors, so their scale isn't 1 currently.
I know that there is a typical thing people do of parenting the player to the platform so that the character moves with it. But doesn't it usually introduce a bug of the character model etc stretching and bugging out if the scale isn't 1?
Not sure how I can make this work and avoid that problem
Change your hierarchy.
Instead of:
Platform (Rigidbody, Renderer, Collider) (scale (3, 0.01, 3))
Do:
Platform Base (Rigidbody) (scale 1, 1, 1)
Platform Visuals (Renderer/Collider) (scale 3, 0,01, 3)
And have the player become child of Platform base
Much love ❤️
Ty
Why pay money when this is free and very good
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i want t watch video
There are videos
https://hatebin.com/zzpqekrtar Hello! sorry if its too obvious but I cannot seem to wrap my head around why my game starts paused and I cannot unpause it.
In fixedupdate
If not paused, pause
Then else
Unpause
Then the next cycle it's not paused, so it pauses
You are doing:
else
{
isPaused = false;
}```
in Update - so every frame basically, that's being set to false.
COmbine that with the FixedUpdate part and you get pausing constantly
i can't find video playlist start from begin
unity learn articles have videos embedded in them.
Uhh sorry that kinda confused me
What I had in mind that I shouldnt read the input in fixed update so thats why i set them in update
and im basically trying to execute them on fixed update
i don't understand why fixedupdate is involved here at all
The game does not stop on update
but I think you're confused about the difference between the else block on GetKeyDown and another GetKeyDown
I tried doing it on update but it was like pausing and unpausing in an instant sorry I didnt mean it does not stop 😄
Hmm all right I will look into it thanks
Delete all the code in fixedupdate for one thing
The if (!paused) part
I expect Update to look something like:
if (Input.GetKeyDown(whatever)) {
if (paused) {
UnPause();
}
else {
Pause();
}
}```
the fact that you have an else on the GetKeyDown in Update is almost definitely not what you want
I used an else if
pointlessly
ahh okay
Oh okay it works now
But my ui scripts that are on the text do not work
also when I press retry the game still starts paused. What is the problem?
idk what your current code looks like
I assume you still have the FixedUpdate thing happening
Ah no I removed it from fixed update as you said
I'll send the code in a min i gotta eat.
what i think is I probably reset the time scale to 1 when I press retry so it does not start paused
You need to do Time.timeScale = 1; in Start()
because timeScale is not going to reset when reloading the scene
hi i am getting massive fps drop like from 800 to 200 if i use spline and animate something on it do anyone knows the reason in editor?
using spline animate
no. profile
For any framerate issues you should use the profiler
Hmm. This will also solve the ui scripts not working? I have text material change scripts on pointer enter
i have no idea, sounds like a separate issue
if your script depends on time scale, probably yes
if they're using WaitForSeconds or Time.deltaTime, then yes
you can use WaitForSecondsRealtime or Time.unscaledDeltaTime to fix
800 to 200 is very small drop
800 fps is 0.00125 ms per frame, 200 is 0.005 ms
difference of fractions of ms
understand that massive over 200 fps numbers are only possible with absolutely minimal load
the more load you put the less and less the difference will be
in fps
you need to set yourself some target ms per frame budget, like 60 fps is 0.0166 seconds or 16 ms
like fixed frames to test?
no, its not fixed its just an arbitrary budget you set for the project
but will also not depends on graphic card or cpu
console games that run at 30 aim at 32 ms per frame
yes ofc, that is up to you to design for min/recommended/max specs
and ensure that the game can run at decent framerates on the hw you said it would
cause rightnow im testing this thing on 4070 but if i go down that 200 will also go down to a lot
not sure why this drop like im just animating one cube on spline
but sometimes some cubes donot move it just stays their
Have you profiled?
not sure how to see the profiler that much but massively i see the other section too much
Not sure what you mean by "that much"
You just open the profiler and see what is taking the most time
You should use hierarchy mode and select a spike
Then dig down to what takes the most time
