#💻┃code-beginner
1 messages · Page 108 of 1
mate your code editor and unity version have nothing to do
it's for every unity version ever made
Because it's not a Unity thing
it's an IDE thing
well it says this
you'll be fine
Oh k, ty
yea, didnt noticed that before, such bad misinformation
(still waiting for peeps to pull you over to VS though)
they're getting rid of mac version of vs
oh mac, that changes things
so annoying having to switch to vscode for my mac
so that's why no "use VS" comments in 😁
Use VS if don't want problems 🙂
or rider if you can't use vs
mac have rider?
android rider is promising
im just poor
just be a student and get it for free. or grab it during one of their EAP times
but actually, ill buy rider if they can do android
ew coding on mobile lol
not that bad if you have work with lots of idle times
anyway too chitchat already, let's drop 
Vector2 screenPos = cam.WorldToScreenPoint(target.position);
Vector2 offset = new Vector2(0, 50);
Vector2 finalPos = screenPos + offset;
transform.position = finalPos;
smth like that
thats like an uneccessary amounts of extra vars with a magic number lol
idk it works
try it on different aspect ratios, that 50 might cause it to break in certain resolutions
smart
oh yeah it does
i just used it for testing lol
hardcoding numbers are nasty and usually will bite you later 💯
how would i get the correct number then?
wait i dunno the whole problem
idk adjust them inside the inspector
this was my original message
but. i think the problem was the anchord pos
wouldnt it still get messed up with different aspec ratios
anchoredpos should be on the canvas no?
ah it was offset, it should be fine as long as it looks what you wanted, thought u are using hardcoded for anchors/pivots
honestly I havent done too much UI to have a straight answer sorry
easy answer: instead of hardcoding any sort of offset, give the object this UI element is follow a child object that the UI object will follow instead and just offset the child object. then you won't need an offset specified for the UI object
well i have it following a object its just for some reason it puts it underneath the object
right so make it follow a child of that object that is offset so that this object appears in the location you want
ah ok
then you won't need to do any addition to get the position, you just get the target's position in screenspace and make that the UI object's position
now i gotta figure out where exactly i want it to go so it doesnt look weird
What callback can I use that works like update but in scene mode?
Update can work in editor btw
just every refresh though
I kinda want a constant thing
nvm, ig i can just use menuitems for this case
what are you trying to do
put tilemap tiles in scene using keyboard keys 
i press w it put wall on where my mouse in scenetab is
would any1 like to assist me in the animation chat
ive been at it for a while
still cant find a fix
could've sworn there was such a class for editor
catching inputs in edit mode?
was this I think
you probably need it inside here though
https://docs.unity3d.com/ScriptReference/Editor.OnSceneGUI.html
this is cool stuff (know it instantly since methods are smallcase lol)
with dictionaries is there a way i can get the just the string inside the brackets. e.g get "string" from [string].
like you have a string that contains brackets in the string? or do you mean something else?
so im basically using a raycast to hit an object and get the string name from that object. string itemToDrop = hit.transform.GetComponent<GroundItem>().ToString(); . then i pass it to another method called addItem which takes the string and checks it in the dictionary.
well for starters, you shouldn't be relying on object names for logic. that's a road that leads to ruin
but the dictionary cant find the item
I'd add my own string field actually, what is it for?
the object also has a scriptable item on it called wood for example
AddItem("Wood", 49); this works
AddItem(itemToDrop, 1); but this doesnt
oh inventory system?
hello!
I'm making my code modular!
Let me make an example
Health stat
% Health stat
They are both stat objects
Is there any way to make Health stat scale with % at an updated value without it increasing infinitely?
probably a curve?
no error in console?
no error just cant find it in the dictionary
thats why im thinking the brackets are including in the check
try to log what it is first before trying to look ipt up in dict
so its trying to check [Wood] instead of "Wood"
instead of guessing if it have [] or not
Debug.Log(itemName);```
thats how i check for it after it passes
log it before, nvm it's a tryget
okay so the issue was actually removing the brackets from a string the whole time and isn't really related to the dictionary.
but still, don't rely on the names of gameobjects for your logic. give your GroundItem class a variable that you can assign the item type to and use that instead
ohh right so its checking "Wood" instead of [Wood]?
sq brackets makes it confusing if you dont apprecite dictionaries being list with keys
Would you mind if i quickly showed you that script cause that leads to a scriptable.
i might have done this the hardest way without even needing to
cause that leads to a scriptable.
no
my apologies
post your !code here
📃 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.
instead of calling ToString on your GroundItem component, you should access its itemScriptable variable (not a very good name btw) then access that object's itemName variable
yea, it's total fail if that thing is cloned
i would personally not even rely on a string to determine what the item actually is. i personally prefer enums for item types
id do both, one for dicts, one for functionality lookup
id rather do strings in dicts than enums
but why?
i see can. My thought was using scriptables as an easy way to change different variables of my item. then just to call it and check it
orange font more readable than enum blue 
with an enum as the key you know there will only be a set number of different items in the dictionary. with a string if you have any that are perhaps spelled wrong (since there's no compile time checking for it) you may end up with a different number of objects in the dict than you'd be expecting
but strings as item name makes itmore versatile in editor
I can easily add an item without having to change code
if it needs a function, like eat a food, only then i will extend my enum
dont have answer there, really hard to find an inventory system to follow
it's an intermediate concept (with a lot of way to implement)
yeah i made my inventory first then tried using scriptables as items and dictionaries to store them just gotta finetune some things i guess. appreciate the respones tho very helpful!
What does that mean?
are you trying to increase the maxhealth or whatever as you Progress ?
add a second float field that is total heath modifier?
thats my understanding of the q
like there's a constant hp, and a percentage hp
Il trying to make my code modular, the %health increase has to manage itself and same for health and I’m thinking of ways to do this since it will be the base for lots of similar stats that share these 2 base classes
oh.. your character parameters are it's own classes
Sounds ambiguous to me. Sounds like you need to establish your anticipated design to know if using an abstract class is necessary or if a StatManager class will work
There is like a base class for a generic stat, like say intelligence then there is a subclass that is called limited stat that has a max value that can be increased or lowered
Im projecting the design on paper and optimizing it before putting it to code
Im trying to make something modular for a long term complex game
I can imagine the concept, idk what the question is though
And I wasn’t using scriptable objects at all which many told me is a mistake
Hmmm I think it’s better shown than explained
nvm,SO can do better
I do not make classes for every stat.
But I make a skeleton of what every stat would need
And then I make a SO to create the stat itself
ye i understand that part, i just dont know what you are mainly asking
you seem to be good enough to implement it
if you asking if it's doable, it is, is that what you need?
There is a subclass that is called percentage stat , and it increases another stat by a percentage based on its base value, what I’m asking is, how can I do that modularly
Cuz if I use update it’s gonna increase it infinitely
If I use start it’s gonna happen only once
ok so here i thought you were asking about a design question
use a float that get's accessed when you needed the field
me too lol
Oooh design whise I scrapped the whole old code and decided to to restart making it modular before it was too messy of a spaghetti.
Idk if it was al the right idea but it felt right.
You could have a base value and a list of modifiers. Each modifier would apply a different operation to the base value. Loop the modifiers and call their apply method whenever you want to get the modified value.🤔
You’re right! Thanks!
anyway, if you're still not totally set on that, interfaces are cleaner way to keep modular data
might as well consider it
I’ll investigate thank you!
Still have to 100% fathom what is the difference between what I am doing now and what I was doing earlier(with prefabs instead of SO’s).
Hopefully I won’t find an event more efficient way that makes my life less complicated and I’ll have to rewrite the whole thing again
we could give better insight if you share some of that juicy codes
It doesn't have to be 100% efficient. If it fulfills it's purpose it's good enough. Otherwise you're never gonna have any progress.
Oh it’s a lot of separate codes and sadly I’m on bed.
I would have to give you a tour of my project haha
You’re right but at the same time I don’t want to be vincolated in the future when I’ll have to introduce something, I want it to be very flexible and having most of the things on scripts like I used wasn’t that.
So I decided to use the code skeleton into SO’s approach.
You can't predict what you'll need in the future and wether it would fit your existing code. The best you can do is decide on the feature set of your app and make sure current implementation is built with it in mind.
You can also always refactor.
There's almost no code that can't be adjusted to fit some new purpose. Especially since you have the whole source code.
Do you feel like my current approach would be even better with interfaces?
My old project didn’t even use subclasses nor abstract classes, it truly was a disaster
I've no single clue what your current approach is. You didn't share any code.
Fine fine let me get up of bed lol
using UnityEngine.UI;
public class HealthManager : MonoBehaviour
{
public int maxHealth = 100;
public int currentHealth;
public Text healthText; // UI Text element to display health
// Event triggered when health changes
public delegate void OnHealthChanged(int currentHealth, int maxHealth);
public event OnHealthChanged HealthChanged;
void Start()
{
currentHealth = maxHealth;
UpdateHealthUI();
}
// Method to take damage
public void TakeDamage(int damageAmount)
{
currentHealth -= damageAmount;
if (currentHealth <= 0)
{
currentHealth = 0;
// Trigger any events or actions for player death
// You can add a method call here or dispatch an event
}
UpdateHealthUI();
NotifyHealthChanged();
}
// Method to heal
public void Heal(int healAmount)
{
currentHealth += healAmount;
if (currentHealth > maxHealth)
{
currentHealth = maxHealth;
}
UpdateHealthUI();
NotifyHealthChanged();
}
// Update UI text to display current health
void UpdateHealthUI()
{
if (healthText != null)
{
healthText.text = "Health: " + currentHealth.ToString();
}
}
// Notify subscribers that health has changed
void NotifyHealthChanged()
{
HealthChanged?.Invoke(currentHealth, maxHealth);
}
}
Example of old code, the healthmanager did EVERYTHING for the health stat
omg
this is the new code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "NewPlayerStat", menuName = "ScriptableObjects/Player Stat/Player Stat")]
public class PlayerStat : ScriptableObject
{
public string name;
public float amount;
public float GetAmount(){
return amount;
}
public void SetAmount(float x){
amount = x;
}
public void AddAmount(float x){
amount += x;
}
public void RemoveAmount(float x){
amount -= x;
}
}```
that can be like cut 1/3
yes i realized that and restarted
and this is a subclass of it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "NewRegenerativePlayerStat", menuName = "ScriptableObjects/Player Stat/Regenerative Stat")]
public class RegenerativeStat : PlayerStat
{
public bool canRegen = true;
public PlayerStat affectedStat;
float timer=0;
public void Update(){
timer += Time.time;
if(timer>=1 && canRegen){
affectedStat.AddAmount(amount);
timer = 0;
}
}
}
still can be simplified, just do a prop setter
wdym?
public float Amount
{get;
set{
amount = value;
// do some logic with value
}```
I mean, that's fine. What exactly do you feel is the problem with it?
Okay, so you want to have a generic stat class?
that's like too much things to remember
my derpy heart cant
I actually don't dislike being verbose on the data being set because when you run into stuff like DealDamage(float value) method sometimes I ask myself do I put negative values in here or positive
yes that and if i want to add something i'd have to bugfix stuff much more, where in this system i feel like thanks to polimorphism and overriding i have to be way less worried
ye, i normally have DeltaSomething() for this matter
Do you need it to be an SO? SOs are more for immutable data. I think it can be just a plain class.🤔
oh, then they are NOT what i tought they were
i tought they were like gameobjects and prefabs but no need to be instantiated
pain.
problem is and what confuses me the most is, you can do that with gameobj aswell
well, it depends how you want to do it. It's not necessarily incorrect to write to them but usually you'd just use a plain c# script
you lost me here sorry
X.X
so since its unchangeable stuff you're saying i should use them for things like
unique items
they're not unchangeable
you use them as if you were to use json or plain text
it's just their stats are decided at the start
oh i see
well ill drop them then
still learned a lot from sublclassses,static classes and such;(they fixed a lot of clutter in my old code)
Now ill go back to bed and watch a video about interfaces.
but you're right on that fact that they are more useful on storing data of unique items
You can treat them like prefabs and create instances of them to write to which is fine.
even use them like a singleton/static class
is better to use always fixedupdate or just update?
but yea, interfaces are interesting if you understand it, you can do
public class Goblin : IHealth, IMana, ISanity
and stuffs
that sounds like dragging scripts into an object?
hard coding capabilities 
like if i want a goblin to walk i'd just put a walking script on him?
oh
ill have to check that
cuz i won;t understand it without scenarios haha
actually, ignore the verbs there, just do store the interface for the stats
the attack, run and walk better go in inheritance imo
I’ll have to check that out cuz like SOs I’m not fully grasping it and I’ll end up using it wrong
But the doubt is the same why use SOs when there is prefabs and why use interface when there is components and viceversa
huge thanks to @slender nymph got it working after some messing around with what u said.
and @queen adder ❤️
Depends, input for update, physics in fixed update. do you have a specific example ?
Oh I get it now it’s like class inheritance but instead of inheriting you only share a method
For sake of polimorphism
using rigid body to move things
Well that’s super useful!!
yes exactly
think of scriptable objects for a card game where each card has the same attributes but different values at instantiation.
so each stats can do differently depending on where they are
Yes I grasped that, my point is can’t I just make a prefab and just manually change the values anyway?
you most certainly can
And what are the differences then?
personally i use fixed update, its almost a requirement when you have fast moving rigidbodies
you can share SO between different things
they're the same, except, gameobjects are physical obj
and SO's are like immaterial
if you put it that way
I see thanks!
So like when an item drops on the ground and is looted instead of keeping it in the scene I can just turn it into a SO?
and btw, avoid using GO prefabs as holders u pass around
public interface IEntity : IAttackable{}
public class Enemy: IEntity
{
[SerializeField] EnemySO data; //can also inject it through an assign/init method for object pooling
float health = data.health; //copy data you are going to change into the class
float attack = data.attack;
//EnemyTags enemyTags = data.tags
//you don't always need to copy data and instead choose
//to read directly from the SO if it's not meant to ever change
public EnemyTags Tags => data.enemyTags;
public Attackable(IEntity attackingEntity) //Required implementation via interface
{
//Attack
}
public ChangeHealth(float healthValue)
{
health += healthValue;
}
}```
that's just not their job and can be nasty if it go wrong
Yep I figured they only work in current scenes
you is typed that for like 10 mins? 🥹
I need to put some kind of on start auto attach on them to fix that
Thank you!! ❤️❤️
it was more complicated before I realized maybe it didn't need to go too crazy
almost had the interface IDoesYourTaxes
Ugh with all these tools the hardest part is figuring out when to use what
I guess that’s been the main issue for me
But yes everything is doable with anything
So far interfaces sound so good for things like Iclickable Idraggable that’s the first thing that comes to my mind
So the inventory system will make me hate myself less at least
if you just want these 2, there's already logic provided by unity for them
but, if you understand interfaces as how they are, it's great
they're useful because otherwise you'd have to type check the implementation, but interfaces guarantees that if your enemy has the IAttackable interface then it must have the method implementation Attackable(attacking entity) and you can directly call it without caring what logic is contained
Yeah and if you want to animate say 3 different things in a given List<> you can just do foreach animate with IAnimable
and likeso, you can pass types around by their interfaces, not caring what the actual type is. This is helpful to group stuff such as all your enemies and allies together such as a list of List<IEntity>
Ooooooh that’s amazing omg I’ll have to theorycraft so much tomorrow on paper
When I used unity some months ago it didn’t have an integrated version control, or better yet, it did have it but it was a hella bugged add on. Is this new one good?
How do I NOT hide the cursor when I click on the play window?
Sorry for bombarding you with questions lol.
you are disabling the cursor in your code somehow
do you use Cursor anywhere in your code?
Oh now I get it
@queen adderNo, I have the 3rd person controller installed, maybe that does it?
what is that? a new unity package?
if so, i guess that does it
cant help there though
yes
Yeah that was it, it is a starter asset
Besides SO, prefabs, inheritancy, interfaces, extension do you think there are more tools that are important?
Okay events I think I know about
But it’s basically interfaces 2.0 with one less step nay?
Like when x Triggers every class triggers Y method
no
x and y can put letters in that box, then you can call that box later, anything inside will fire then'
if I use fixed in one script i need to use in all the others?
Oooh I see so its for things that share a method like prefabs and interfaces that are in the scene?
omg they are their own thing, dont connect them to others
they just can hold methods, doesnt care where from, as long as the methods match them, they will hold it and fire when you want\
if you want to do something when your main character die
have a delegate hold it, then fire when the player die
or if you want the goblin king to get mad when you kill a goblin, have a goblin register their deaths to the goblin king,
https://gdl.space/iqebofoyup.cs got it working after some time lol, need it? @rich adder
Thanks!
don't mind if I do 🙂
going to come in handy , making some editor tools
thx!
I 100% hope my tile pallete isnt so slow for me though that I needed to go make this
i prefer string than enum in inputs (because vsc sometimes do weird suggestions)
esp in editor things
I do change it on final builds though
yeah I'd make an abstraction class for rebinds but I'll stick with enum
was just wondering if Event.keyCode worked, i'll just try it out ig 😅
If its rigidbody movement I would always use fixed update unless you have a good reason not to. The only thing that can cause more crap is if you have any object positions that need to be synced that run in different update methods. rigidbodies are normally used in fixed update for consistency in physics calculations.
answer is, fixedupdate and update have their own jobs
update are guaranteed per frame (it will catch anything that happens)
fixed only happens at physics interval
Any good tutorial on how to use interface?
imo lookup traditional c# ones
this is my first year of game design and programming and i tried doing this assignemnt but i couldnt understand it
Check out the Course: https://bit.ly/2S5vG8u
Discover 5 different ways to move your Unity3D gameobjects, see some of the differences between them, and learn which one I usually use.
More Info: https://unity3d.college
this guy is good though for gamedev
https://youtu.be/-asqmmY-FUM
2023 Game Dev Course - https://game.courses/bc?ref=15
Fantastic Fantasy Asset Sale - https://prf.hn/l/me3dPA0
00:00 - Introduction
00:21 - What are Interfaces?
00:56 - Why they Exist
01:20 - IInteractable Example
02:12 - MonoBehaviours & Interfaces
02:40 - Plugins / Mod Systems
03:50 - Unit Testing
04:47 - Event Systems
movement of which video ?
also that youtube channel is pretty good, which part do you not understand ?
although that video he don't put rigidbody movement in fixed update which is wrong
that assignment looking a little overdue
i got past the first one then in the middle of the second one he switched to somthing else in the play view
i was copying what he did exactly but when he got to that part
my stuff broke
🤷♂️ whatever that means
ill try doing it again right now
now thats a true programmer
very 
doesnt say what year though
u is safe
lol
could be 2079 or could be 1990
i wasnt even in existance then
wait unity didnt block the "lol", i remember server blocks short comments
bug?
mayhaps
ok imma go work on it, ill send a message here if it doesnt work
thank you
regex is a hit or miss sometimes
also the mods put it not unity lol
regex is handling it?
yup
oh my god, i dont even have microsoft visual installed on my laptop
how do i install it again i forgot
!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
thmank
Probably a dumb question but how would I reference the collider of a gameobject in a script that isn't attached to said gameobject?
you’d have to have a variable of the gameobject with the collider
No the other object is just an empty gameobject with a collider attached, no script
yeah ik
Oh sorry I thought you were asking me if the other object had a variable, I misread
public GameObject collider_object;
fill it in in the editor
collider_object.getcomponent<>
i don’t really remember the exact syntax but you get the point
I'm making a tetris-like game, but when the pieces aren't 0 degrees, they don't fall down.
show code
[SerializeField] private Collider col;
and you mean are 0 degrees
there’s no way of filling it in though
what are you talking about ? do you even unity lol
Testing that one now
Hello guys do you have any article that advises about good practices and mainly patterns for Assets folders and Hierarchy?
the only way that isn't possible if the said reference was on a prefab and you want a scene collider or vice versa
its mainly preference Imo
i always put my script folders as _Scripts they're always ontop the project files
same with _Prefabs
Visual Studio
? did you configure it
Can you take a screenshot of how it looks like in the ide?
Yep, that worked!
Sorry forgot that SerializeField was a thing
You need to reset rotating = true
I think I formatted it
It's falling down, but only when the degress is 0.
You don't need to do it manually. Your ide should do it for you.
Well I forgot.
scroll up
private void OnTriggerEnter(Collider other) { Debug.Log("test"); if (other.CompareTag("Snowball")) { currentHealth = currentHealth - snowballDamage; Debug.Log("damage taken"); } else if (other.CompareTag("Gift")) { Debug.Log("Work"); CameraEffects.ShakeOnce(); currentHealth = currentHealth - snowballDamage; } } why is this ontriggerenter not working? when it hit the "Snowball" object it does register and subtract the health. but when it hit the "Gift" object, the Debug.Log("test") is printed on the console but it doesnt subtract the health or print the Debug.Log("Work")??
this code doesnt move anything anyway @tender breach
Yes but you never set Rotating to true after it goes false
two backticks
📃 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.
That's not the issue. Whenever the degrees of the piece is 0, it falls down, but when the degrees is 90, it goes left, and when the degrees is 180, it goes up.
oh
Where/how do you move it?
It doesn't sound like physics is moving it.
you can have a gameobject set always at 0,0,0 rot and a sprite child that’s the actual piece and it rotates
and move the one always at 0,0,0
Examples of where?
In code.
I don't understand.
I use code
You must be moving it somewhere, otherwise it wouldn't movem
show it
Share that code
lol
what on earth is that formatting
the "Gift" (the particle with large collider set to is trigger) object is clearly hitting the other object i attached that script with (the other object collider is not set to is trigger). what's wrong?
this isn't the moving script
still waiting on that screenshot for vs to confirm
That's the same thing you shared earlier.
They are different scripts
you should first format your code properly, because there is no way you can clearly understand what its doing
you're using worldPos
What do you mean?
regardless of rotation its gonna go same way nvm then hah
How do I fix it?
Transform.translate would move the object in local space, so if it's rotated, the movement direction would rotate as well.
At this point, I think you should follow a tutorial...
wait is default local?
For translate, I think it is🤔
I tried tetris tutorials, but they had similar code.
https://unity.huh.how/physics-messages
go through this for your physic message problems
Similar != The same
could be , just remember having to use the Space.Self, but i barely use it honestly]
Docs say it's relative to self by default
ah ok forgive me then 😅
That's fine. I don't use it either.
then you actually want the opposite of what i said
put it to world space direction, so keys always put it same direction regardless of rotation
Okay so I know that worked but is there a way to do it in code without SerializeField?
Dependecy Injection
assuming the only way you cant use serialize field is the object is prefab and ur referencing something in scene or vice versa
otherwise you should be using only serializefield, no reason otherwise .
Maybe TryGetComponent for other realtime stuff
whats the use case? if these are completely unrelated objects where you cant use [SerializeField] then you would likely be getting these through some physics functions like raycast or the physics messages
how do i pause only the vector movement and not the animation in unity?
pause vector movement? wdym
i mean, i just want to pause movements of gameobjects
all i could think of with limited info 😅
ah no problem
im trying to write a bit of code that makes the projectiles destroy when they hit objects other then their clones all the layers are set up and its still not working could i have some help?
go through this
https://unity.huh.how/physics-messages
i literally don't do anything but now the Debug.Log("test") is not printing anymore??
sounds like you did something, still the link would be useful to tell you why nothing is debugging.
What may I have to put on Awake method and Start method? The same for Update and FixedUpdate?
What are you asking exactly?
They are pretty different, in that start and awake run once in the objects lifetime, while update and fixedupdate run many many times
The main diference about what kind of code I have to put inside each one.
You dont have to put anything in them
You don't have to do anything
Things that you want to happen once go in start/awake
Things that you want to happen over and over go in update/fixedupdate (some caveats here)
ok... I have one thing that happen once, when I call in Awake, when I call in start? The same for update ones.
Generally Awake is used for gathering references/early setup, Start is used to act on that setup.
Update is self-evident, and FixedUpdate is for physics.
Not really sure what you're asking still, sorry
let me give a real example
They are special methods that are detected and called automatically by Unity
I have one player variable like total HP that is intialized one time... where should I have to put in Awake or Start? I have a GetComponent to get for example, a AnimationControl... where I have to put?
What question I have to make to decide where I'll put the code that is called only once
All of that in awake or start. Doesn't matter too much.
Generally awake though, because it is a self-reference
Why is total HP not initialised in the declaration/inspector?
because comes from database
I have more than one player and each one have its own total hp
Ah, is the database needing to be initialized in memory?
Maybe do that earlier stuff in Start to give the database time to finish whatever it needs to do
with databases ideally you want async
unity is meh with asyc tho so ig coroutine too works
they have async void Awake() 😬
make an init method and just populate that until ready
Hey, how would I do a yield return new WaitForSeconds(timeF) but if a bool is set to true do a different function?
So it interrupts and stops the waitforseconds
nvm
Ik how to use wait until a bool is true, but I don’t know how to do both
i dont understand why wouldnt a regular if + else work?
if(somethingTrue) DoOtherThing(); break;
Hey Hey!
I hope everyone is well, it’s currently 4AM and I’ve had an idea for a college project however, I would like some ideas/advice on how to construct it, you could say.
The idea is a checkpoint system where UI is used, if the player has reached this checkpoint, unlock it on the checkpoint selection menu and then when they load in again, they can choose to go from that checkpoint.
if (bool)
yield return WaitForSeconds(10);
else
yield return WaitForSeconds(20);
?
You could use coroutine.
Ok I need to explain better, you guys obviously can’t read minds (I’m meaning this literally not an insult)
What?
This IS in a coroutine. And I'm answering someone
knowing the use case sure wold be useful 🙂
I have no clue what you were doing, seen a delay and suggested coroutine.
OH
OOPS
ITS 4AM 😂
don't use WaitForSeconds, instead use yield return null; inside of your own loop that counts, and break out of the loop based on a boolean
or use WaitUntil with two checks, one against time and the other against the boolean
Or switch to async, learn how all that works, and use a cancellation token 😄
I am using triggercolliders, how can I call "other.MyCustomFunction" on the object that enters the trigger? Ofc trigger script does not know if MyCustomFunction exists or not beforehand, so need to see if it does before calling
So I have a bool
saveMeTime = false
When my character crashes it runs a coroutine and needs to wait for a specific amount of seconds (5.95f in my case), then it runs some other stuff under that. But I’d like that to not happen if I use a saveMe (revive) function. So what I did was create that bool, and under the wait for seconds I put
If (saveMeTime == true)
Other balalalalaaa
That works great. But what if I crash and revive, then crash very soon, the wait for seconds hasn’t finished yet so then it will run that code too early because it sees saveMeTime as true
I put saveMeTime to true at the beginning of the crashing coroutine
You should cancel the old coroutine
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html (use the one that takes a Coroutine object)
Coroutine routine = StartCoroutine(Method());
(Not the best way, but just an example of how to cache the coroutine in order to stop it)
Sounds like you just want a save system.
Writing to a JSON file is a decent choice
I’ve done a lot of attempts to try to stop the coroutine, but it seems to not work. I also don’t know how to rephrase that coroutine because it has
CrashCoroutine(string anim) (I have something for it to determine it’s an animation already)
So when I need to run that corutine I have CrashCoroutine(“fallAnimation”)
When I rephrase it it gives me errors then, I’d also have to change all the other parts in my script to match this new rephrased coroutine
Pretend rephrase says cached
What exactly did you try to stop the coroutine?
Here's my complicated "how to stop a coroutine and track whether one is running" page https://unity.huh.how/coroutines/stopcoroutine
This looks pretty helpful, thanks
But my coroutine has
CrashCoroutine”(string anim)”
I have no idea what that means or why that stops you from using this method in any way
If you're talking about passing a parameter to the coroutine, just do that
I get an error that says
There is no argument given that corresponds to the required parameter ‘anim’ of ‘Character.CrashCoroutine(string)’
and did you pass a string to your coroutine?
Yes
Show your code then
I have some navmesh agents I move on click, and I spawn like 100, but some are really slow at moving while the other 80 are going in a huge blob, the rest are kind of lagging behind and not moving to the point
From a quick google search I saw that apparently there is a limit of around 100 agents until they start bunching up
Bottom answer here https://discussions.unity.com/t/how-many-nav-mesh-agents-can-i-have-in-a-scene/189143/2 @robust condor
My computer is taking a while
I’ll send a short example
private Coroutine deathPlayer;
void Start()
{
deathPlayer = StartCoroutine(DeathPlayer()):
}
public IEnumerator DeathPlayer(string anim)
{
WaitForSeconds(f):
Functions
}
If I make them kinematic they will move where they need
You're calling DeathPlayer() without the string argument, as I asked
You mean to put it like
deathPlayer = StartCoroutine(DeathPlayer(string anim));
?
No, that's not how you pass an argument to a function
You'd only need the type if you're declaring a new variable or casting - not including class member definitions and whatnot.
Your function is declared as DeathPlayer(string anim), it needs a string passed to it. Either pass a string variable DeathPlayer(MyString), or use a string literal DeathPlayer("Example").
I need string anim because I declare the animation name in other parts of the script when running the coroutine
Then pass it to your coroutine
I don't know how clearer I can be. You declared a function that takes a string, you never passed it a string. That's an error. Pass it a string and the error will go away
is the IDE not even underlining this
public String foo;
deathPlayer = StartCoroutine(DeathPlayer(foo));
Will
deathPlayer = StartCoroutine(DeathPlayer(""));
work because I have no errors
sure, that is an empty string
Are you trying to pass an empty string?
What do you WANT to pass in? It's your code
yes
Ok then sure. Not sure why you would want that, but have at it
k ill try it
here is previous code
StartCoroutine(DeathPlayer("stumble_lower"));
how would I use that new cached coroutine tto use it like this
stumble_lower is an animation
... literally the same way
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
StartCoroutine returns you a Coroutine
ohh wait i think i get it
you're just storing it in that object to be able to stop it later
how do i fix this bug it not following the player and rotates weirdly
!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.
Please link to large codeblocks
ok
You'd reference it so you can refer to it later when you'd want to stop it #💻┃code-beginner message
I have a script I want to have on all my NPCs, do I really need to add it to all prefabs? Imagine if I make a new script and have 200 prefabs I need to attach this script to
1 prefab 200 SOs (or 1 prefab 0 SOs and 200 serializedReferences)
You can use a base prefab that all NPCs are variants of
You could use nested prefabs or prefab variants.
Or what Mao suggested.
I believe theres even a way to make an existing prefab a variant of another?
Ideally, you don't want to configure every single npc by hand. They should be generated at runtime from data.
I tried to attach a script a game start to all tags "NPC" but it seems that is not supported when I googled
On spawn of the NPC I mean, instantiating
That's possible. But not ideal since the newly added NPC component will have default values
Sure it is. Show your implementation.
Not an issue if all of the NPC data is in a SO, though. Just assign the SO
How do I reference my other c# script?
Inspector field of the manager doing the instantiations
You wouldn't need to reassign references if you have a "placeholder npc prefab" that has all the required references set. You just need to setup it's visuals, stats and whatever other data that is unique to the character.
@ivory bobcatI can't drag my C# script into a SerializedField
Why not?
Are you dragging in the script file itself? Drag the object that has the component instead
So I need to have a gameobject in the scene just sitting there with the script attached?
I fell off the tracks, what is this other script?
Is it not serialized, not a reference type or?
So I have my NPCManager, and NPCSpawner GO, they are two different scripts, in the NPCManager I have a Speech script, now it is a GO child of NPCManager and Speech is the only script on it. Then I want to add to every new spawned NPC by NPCSpawner so I can call .SayText()
Ohhhhhh I get it now. Doing
deathPlayer = StartCoroutine(DeathPlayer(“Animation)); is the way it functions, just like regular start coroutine, thanks!
I was able to put the GO with my script as reference in the inspector, not a raw C# script itself
If you just need to add a component to a gameObject, use AddComponent.
wdym by a 'raw' c# script
Script file I assume?
From the Project folders
like a monobehavior or a poco
Anyway, as dlich said you just need AddComponent with the correct type as parameter
using UnityEngine;
public class SimpleFloating : MonoBehaviour
{
public static bool animPos = true;
public Vector3 posAmplitude = Vector3.one;
public Vector3 posSpeed = Vector3.one;
private Vector3 origPos;
private float startAnimOffset;
void Awake()
{
origPos = transform.position;
startAnimOffset = Random.Range(0f, 540f);
}
void Update()
{
/* position */
if (animPos)
{
Vector3 pos;
pos.x = origPos.x + posAmplitude.x * Mathf.Sin(posSpeed.x * Time.time + startAnimOffset);
pos.y = origPos.y + posAmplitude.y * Mathf.Sin(posSpeed.y * Time.time + startAnimOffset);
pos.z = origPos.z + posAmplitude.z * Mathf.Sin(posSpeed.z * Time.time + startAnimOffset);
transform.position = pos;
}
}
}
So, I have this code.. i reference this script in another script and whenever i want to pause game, i put animPos = false (because i dont want to pause some animations)... But whenever i resume game by making animPos = true the gameObject position is reset... How do i stop the resetting ?
Okay now it added the component but the default values are broken, should I set them in the spawner script where I do addcomponent or can I use another gameobject for the settings, or should I use a SO?
I pointed that out here
I need to reference a canvas and a tag
And here
Okay will try that then
If you need to reference something in the scene then you need to do it via code (in this case, since you add the components dynamically)
SO assets or prefabs can't reference scene objects
The spawner script could hold the reference to the canvas, I guess
If it's a shared canvas and not instantiated for each NPC, that is
Oh okay
Is it better to add an empty class to a GO just to reference it and find it by type or should I use the GO name?
100% Type
don't ever use strings like that
Why do you want to reference it?
If you just want to use SetActive then referring to it via a GameObject reference is fine
never use names, but you can just refer to the object just fine
Maybe I am dumb, but why is my player capsule getting significantly slowed when in a moving platform?
we can't possibly know that without scripts/setup 😅
I have an script to parent the player to the platform when on top of it, so it keeps it on it and another one that moves the platform with transform.Translate
parenting the player isnt such a good idea, it doesn't make a whole lot of sense because you especially dont want the player scaling and rotating around the center of the platform.
Have the platforms either apply some movement to the player, or add to some vector on the player movement script to tell it what it should be moving by
I literally just copy pasted that from a tutorial; it worked perfectly before XD
before what, you just said its significantly slowed
true not for nothin many tutorials do use CC parented to platforms
beginner tutorials are mostly shit
most of them are copied off each other, doesnt matter the quality of the content. for youtubers it is a matter of publishing work first and screaming to be seen
yeah kinematic rigidbody would be best bet prob
I changed the code of the parenting of the platform so it also works with some stuff that needs to be dragged around; but since it did some weird things with the scale; I had to change the whole hierarchy attaching all the scripts and the platform itself to an empty object with 1 as scale
I think is cause the player doesn't like to be moved with a translate from the parent and a AddForce from the player controller
Don't really know how to work around that
idk why that message link isnt shortening 🤔
then start learning, if you give up before trying to learn vectors then honestly you might as well go do something else.
You use CharacterController? Or rb?
Apparently RB. Yeah rb does not like being parented to a moving object. Unless it is kinematic then it is fine
if a specific part of what i said above is confusing, you can ask and i can try to clarify. But i cant really suggest anything since you havent shown the movement code
The basic movement script is no more than rb.AddForce on the input vector; nothing more
I can share if you think it might help
I think with addForce it might be a little more difficult because you arent directly in control of what the current movement vector should be. Like if you addForce once, it can technically just keep going forever.
You might have to change a lot to get proper platform movement
You put < > around it.
probably by habit from other links. I do that too lol
What I do is just assign directly to the .velocity what the current movement should be, so this would be easy to add platform movement. A platform would just add to some vector on the player script. then in the player script it'd be as simple as
rb.velocity = movement + externalForces every frame
ah, it gave some embedded thing before which is why i did that
Could it work if I set the player velocity to be its own velocity + the vector of the moving platform translate though?
not its own velocity, otherwise you'll quickly hit infinity. it would pretty much be what i said above. you cant really combine moving the transform and rigidbody movement. things will break like your rigidbody might start jittering, your camera might start jittering, player might be able to teleport into objects.
Could also do normal movement + rb.MovePosition with the platform's movement
So we just don't move players with addForce then?
If I were to have projectiles that used rigidbodies for continuous collision checking, how would this this apply to objects using character controller movement?
my console keeps spamming this error, can someone help me?
^ try resetting the error otherwise sounds like maybe a material broke
I wanna say
and tell us
that requires precise testing :(
Maybe speculative is the best option here?
Works well on netcode at least, idk how fast yours are tho
Since ContinuousDynamic needs the other objects to have Continuous according to doc
https://docs.unity3d.com/ScriptReference/Rigidbody-collisionDetectionMode.html
I cant manage making my own interpolation checking it's just bad
was trying some raycasts and a spherecast but there's a lot more math to it I feel
and ive no clue how to sync that all up
raycast backwards from back of bullet?
So I have a trigger collider, when an NPC enters this collider I want to call a function on my NPC using Collider other.SayText("..:") but the trigger doesn't know of this function.Should I use events or should I check what type of entity enters the collider and search for my Speech script on other? Or perhaps the logic is best reversed, have the NPC do the SayText when it enters the collider?
Tunneling is the term for this if you didnt know @timber tide
Or anti-tunneling
If you wanna search for some resources
Should be engine agnostic
probably have a textspeech handler on the enemy
ye I do that too but if there's many other colliders in the way then it registers pretty badly on what it hits.
@rich adderI have a SpeechHandler on my NPC, but if I have two different trigger colliders, how do I know which one it entered?
Could always ditch CC and go with a RB 🤷♂️
Have them on different objects
You can't know which trigger it entered if they're on the same object
Then just do TryGetComponent
truth
it's a special CC though for A* project that I've been appending upon
helps with avoidance than just bumping into crap
they don't give you like the path / direction between each node?
@summer stumpI have two prefabs, one is house and one is a mine with box collider trigger, NPC walks into one of them and it triggers the OnTriggerEnter script on the house. Should my trigger script use TryGetComponent<SpeechHandler> on the "other"?
Yeah, that is one way to do it. If they are THAT different, it may be worth doing a quick CompareTag first though
there's an illusion of collision but I still can affect them with my own forces.
I was imagining you had multiple trigger colliders on one object
I am also doing if (other.tag == "NPC") {
it's interesting but it helps from enemies getting stuck together
Ok, well that should narrow it down, then yeah do TryGetComponent
Your npc sould only display whats stored in that particular linked trigger
So best practices is to make the trigger say the NPC text, instead of the NPC itself?
SpeechHandler should ideally only Get that text from the triggers
if (other.TryGetComponent<SpeechHandler>(out SpeechHandler hit)) {
hit.SayText("I am relaxing at home!");
}
No the npc just is a "client" of speech aka it only plays back the speech
grab the speech from the trigger
since they all vary by locations
Always use CompareTag("Tag") instead of == "Tag", it's faster and it produces errors when tags don't exist
Alright
Much better than tag yes this keeps it more generic
but you should store the text in a variable, so each trigger can contain different strings to grab
With interfaces you can make it even more generic
public class NPC : MonoBehaviour, ISpeechHandler { }
I get Tag is not defined with CompareTag, despite it actually having a tag check I click on it in the scene... when I spawn the NPC gameObject.tag = "NPC"
Wait, you say Tag is not defined, did you do CompareTag("Tag"), ie. my example, instead of CompareTag("NPC")?
Hehe oops 😄
console keeps spamming this error when entering play mode, can someone help?
I can only assume you've some material with unassigned / null properties on one of your gameobjects
maybe a texture
or rather the material reference is bad
If restarting doesn't fix it, I would guess that if you're using a render pipeline, the asset/renderer is busted somehow.
There are a lot of warnings (disabled/hidden), presumably they would also help to figure it out
!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 make character rotate, but it started to do this when i jump, everything worked before..
https://hatebin.com/cimzlepjlf
Are you sure that's not part of the jump animation itself
i want to create character controller
so i should use character controller or rigidbody to move character?
Depends on multiple factors, each has their own pros and cons
dani use rigidbody in muck
and i want to make a game like muck
so should i use rigidbody?
If you choose Rigidbody you get
- Built in Gravity , Drag etc.
- Can easily interact with physics objects
If you choose Character Controller you get
- Can easily handle slopes , steps
- Easy to make it snappy
- Also doesnt get stuck on walls
for the most part, rigidbody moveposition and other methods would be implemented similarly to how you just do general direct transformation movement but instead of delta time we'd use fixedDeltaTime, right? How about rotational methods like quaternion.rotatetowards/vector3.movetowards and similar methods?
ofc, it worked before i added rotation code
rb.MoveRotation/rotation/AddTorque/AddRelativeTorque
Oh youre asking whether to use deltatime there?
oh let me take a look at your rotation code then,
more that if I can plug in rotatetowards or am I required to lerp with move rotation. Oh, maybe they're similar
thanks, I think I choose rigidbody
if its kinematic, then it is the exact same as affecting the transform but you just use the rb methods. MovePosition just gives it velocity temporarily during the move
You can combine rotatetowards and moverotation if you want
Moverotation just sets the rotation while using interpolation
I'm just trying to move a lot of projectile logic to RB to try out the collisional checking
By mistake I have done factory reset of my pc which has all unity projects so would I be able to backup them???
let me guess, no version control or stuff on github?
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
Nothing, backup doesn't exsisted
Do your projectiles need to be rb? One solution is to use raycast, you can make it travel over time also.
Or spherecast if the projectile needs to have "volume"
if the files are physically deleted what do you expect
Today my crush also told me to use unity and my pc is full of trash so I done factory reset 😭😭
are you sure files are deleted and just only apps refreshed
Backup by acc
did you check off to delete all files?
Ye
well, uhh, i know that data from disc can be restoreed, they are still stored on disc and waiting to be replaced, watch youtube videos ig
Hm does the memory still get cleared by a factory reset? maybe you can hire someone to go through and restore from your drive
I don't need rb beyond checking collision. I've a lot of high speed projectiles which don't just fly straight so it's been quite tricky to get right.
but if you're a very beginner and didnt have much, you might honestly just wanna start again. as you dont wanna fuck up ur computer and it might take time to do this
you can try one of those hard drive scanners for deleted files
tehcnically your files don't delete from HDD unless the space gets overwritten
First step is to stop using that computer. The data is still there but free to be overwritten if you use the disk
You would likely have to hire someone to go through it for you though
i said same thing
#💻┃code-beginner message
@fringe plover So what you are basically trying to do is rotate the character in the direction of where we are going so if I press "A" for eg it should rotate left? Is that right?
I gave a prefab with a rect transform, but the position of it gets reset everytime I instantiate the prefab as a child. Why does it not say at 0,2,0?
I personally use raycasts so I dont have to deal with fast moving RB's
My projectiles move at realistic speeds (300-1000m/s)
I didnt use any fancy math for the trajectory, I think I just add a gravity to the velocity when I update it and some drag/damping
just add a script to the prefab and set it to where you want manually
yes ig.. i just used code from tutorials, i dont even know what Helper class do
@timber tide I raycast the projectile forward each FixedUpdate and have a visual object that is interpolated in Update
Not saying you have to do this - its just what I settled on
What are the parameters of your raycast though? I can't seem to formulate mine to make sense for how long this raycast should be.
Just have a velocity vector3 in the projectile and use that as the direction, and its length as the maxdistance
You set velocity to the shot direction when shooting ofc
Well the helper class's .ToIso() method convert's a 3 component vector into a quaternion with 4 components so it's just fancy math to convert a vector into a quaternion.
But I think the code for what you are trying to do should be a lot simpler
Wait let me refactor your code @fringe plover
@timber tide if projectile hits nothing after ray, move it to its current position + velocity
i can send prefab if u want...
There's also times where I frame drop and it completely skips a bunch of colliders, but I've not been doing anythign in fixedupdate which could probably be related.
Thats why fixedupdate is cool, it runs pretty reliably
So clean
sure, that would be helpful
If your frames drop, the physics sim will still (try to) run as many times as needed to catch up @timber tide
illl make zip and send in dms
ok
I would think update is more precise though if it's checking more than fixed, but perhaps my assumptions are wrong for how update is working with my transformation movements
Colliders dont update between physics updates, not by default anyway I think
Also remember... fixedupdate can run more than update if your frames are under 50
(At default setting)
Yeah, I know but why does a lot of tutorials and even the documentations show a lot of general transformation movement without fixedupdate
there's very little reason to do it out of fixedupdate if you're dependent on collider information
Those thing arent physics related most likely
I think fixedupdate makes more sense for this if you have rigidbody movement
For me it works like a charm
it makes sense if you're using rigidbody methods, but even for collider checking
its still a physics function though, would it have up to date information if colliders move every frame?
I dont like it to be frame dependent so just ditch update
if collider info is updated via physics updates then I guess I should just shift all my code over to it
I think it depends on a setting in the physics
Which is best hrurp or urp???
because my very fast projectiles do eventually clip through walls and even with some determination through raycasts, any framedip makes it obsolete.
Okay I'll ask my crush
i pretty much just do this in fixed update. I think I might have to add a overlap check at the start because i realize this might have a rare case where it can miss
bool didRayHit = Physics.Raycast(
transform.position, direction, out RaycastHit hit, speed, damageableLayers);
lengthTravelled += speed;
transform.position += direction * speed;
Yeah thats my basic idea too
Is there much difference in urp and hdurp?
this isnt coding related at all, you really dont need to spam as well
i guess i am your crush then
do you also overlap check? not entirely sure if i need to but my thought process is:
it may raycast, not see anything, moves the position
something else moves into that position at the same time
the start position is overlapping an enemy, so 3d raycast ignores the collider and it misses.
I'll probably give kinematic w/ moveposition a try eventually, but for now I'll probably just shift it all over to fixedupdate
I dont, I havent noticed an issue when playing against bots in single player
But I think I get what you mean, I need to do some testing
even the forums there's a bunch of mixed opinions on the best way to handle this stuff
at high speeds i can imagine its a very rare bug if it does exist
Could be noticeable on moving targets from distance though
Might be solvable with execution order too
Move all players before moving projectiles?
i see the same things when it comes to talks about how to handle melee attacks too. Im sure theres a lot of ways but some ways might just be harder or have small edge cases
_RectTransform.anchoredPosition = new Vector3(0, 2, 0); does not set the Z to 0, it spawns at -900 something, what gives?
@eternal needle I could do a second raycast back to the previous projectile position at the end of fixedupdate 🤔
In case something moved there in the meantime
its probably not worth worrying about, if it happens then visually it'll probably look more like the projectile just missed the enemy. The enemy would have to move its entire collider worth of distance every fixed update, for it to be an actual noticeable issue
I think it would just make sniping moving targets etc. more forgiving (which I want in my case)
If there was quite a radius to the projectile, I guess you'd sphere cast many times ahead or perhaps just use a few more raycasts to cover the area
hmm I think the raycasts would probably be more performative because otherwise I'm looking at 8-10 spherecast to cover the area hah
Spherecasts are a bit costly yeah
the anchored position isnt what you think it is. you likely dont need to be directly setting the position anyways
https://docs.unity3d.com/ScriptReference/RectTransform-anchoredPosition.html
I was thinking just still raycast but do an overlap sphere to check before if it is colliding with anything
Theres also SphereCast/RaycastCommand for performance, havent implemented it myself yet
https://docs.unity3d.com/ScriptReference/SpherecastCommand.html
yeah that makes sense
what is the best way to pause a math function?
wat
Dont cross post
I have been trying to get tmp text to look at the cam for an hour now, but it is tilted:
private void LateUpdate()
{
transform.LookAt(_Camera.transform);
transform.RotateAround(transform.position, transform.up, 180f);
}
I think there's a component that does that for you
rotate around is probably causing that, why are you rotating it around itself
Because otherwise it is mirrored
then that is something you should fix in the inspector
I don't really understand the rotating, shouldn't lookat suffice here?
@eternal needleI instantiate it dynamically
yes LookAt alone should be fine, thats all i use for doing the same thing
then fix it in the prefab
what does the position have to do with the rotation, your text is just backwards in the prefab
Is the script on the same object that has the text?
I tried flipping all values
TMP added it
Are you using the UI version of TMP?
No
Theres a world space version too
I think this would have to be in world space yea
That is all it adds by default
I don't understand why do you have everything under one objct
Oh apparently it uses recttransform now okay
@timber tide @verbal dome incase you were interested, i tested this on my navmesh agent running directly towards me. I think about 1/30 of the projectiles didnt hit without the overlap check. All of them seem to hit with the overlap check, but its somewhat awkward on what size to use (since raycasts dont have width). With overlap sphere and a radius of 0.1f, 1/5th of my projectiles were hitting through the overlap instead of the raycast.
I can't remove the rect transform
This is for 3D world space above characters head
Where do you overlap again exactly? At the shot start position? Or along the first ray?
I'll probably fool around with a larger spherecast than needed and do some positional calculations to fine-tune some of the stuff.
my code is a little shit cause i just wanted to test, a bit of the code is related to other stuff but this is what i tried.
https://gdl.space/osizirekeh.cs
Check to see if it travelled already (length > 0) so it doesnt try colliding with my player
Overlap check, if it hit anything then return early
Raycast
i might change that first part so it checks if it moved more than 0.1f, which is the radius i used
Im a bit unsure still what problem the overlap solves
But Im also sleepy
So theres that
Maybe it'll click for me later today/tomorrow 😄
my paint description if this makes sense
in the first part i meant it doesnt reach the enemy, not misses but i cant edit text in paint lol
Could also just use Physics.queriesHitBackfaces = true, right?
Nah I get what you mean
This will work for my case at least
i was thinking that, but is there a way to apply that to one raycast? or would you have to set it true then false afterwards
Gotta set it to false after because it is static yeah
No biggie
Thanks for pointing this out, I was thinking of something slightly different before
Didnt think of this edge case
np, i only thought about it because of your past conversation with mao, and was working on my ability system
mr.materials[2] = cardFront; // This line does nothing
Debug.Log(mr.materials[2]); //Returns same material as before
Anyone have any clue why this might not work? I can change material on the mesh in the inspector just fine, just can't manage to do it in runtime, can there be something wrong with the mesh? Import settings? Throws 0 errors btw
materials returns a copy of the materials array
So you need to get it, then modify it and then assign it back
@verbal dome yuuup. Thank you
If I want 1000 combinations of my character models, should I load all possible clothing, hair etc. in one prefab and then randomize the selections on spawn and hide the rest on every character spawned?
now imagine if you have 100 characters in one scene
each having 1000 combinations
each combination contains X different objects
result = milion object
Can someone look over my Code? I feel like somethings wrong and I can't put my finger on it.
@rare basinSo what to do, delete all the children that are not selected?
spawn only the neccesary objects for instance
Maybe a system where you have scriptableobjects with data for storing the clothing type, IDs and prefabs of each item, then when you want to load the character just choose from the SOs you've created, get the prefab and spawn it to the correct position
The more information, the better. Other than that, just ask/provide the question/problem rather than ask if someone's willing to do it.
You could for example have a struct ClothingInfo and store an array of clothing SOs and a transform that is positioned where the prefabs should be spawned
I've managed to set some testing up, but I'm kind of confused on the consistency of speeds here based on the timestep of fixedupdate. A timestep of 0.02 makes my previous values I've had in update much, much quicker.
Then have an array of ClothingInfo and from each item, choose a random SO, instantiate it and parent it to the transform within the ClothingInfo
Sorry yeah. Basically, I'm making a small Whack-a-Mole game, the function is meant to be that once the player goes to the table they have to press E to Interact. So far so good, I feel like I'm processing the code completely wrong and having a form of Overflow because my Game crashes imediately after I press E. Something I'd like to mention is that I can't open my game anymore since I changed my Code slightly...
Game Object (1) is my Trigger and Box-Collider.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class WhackaMoleStartUpdater : MonoBehaviour
{
public GameObject otterTop;
public GameObject otterMiddle;
public GameObject otterBottom;
public int counter = 0;
void Start(){
otterTop = transform.Find("topotter").gameObject;
otterMiddle = transform.Find("middleotter").gameObject;
otterBottom = transform.Find("lastotter").gameObject;
if (otterTop != null && otterMiddle != null && otterBottom != null){
if(otterTop.activeSelf || otterMiddle.activeSelf || otterBottom.activeSelf){
otterTop.SetActive(false);
otterMiddle.SetActive(false);
otterBottom.SetActive(false);
}
}
}
public void WhackaMoleGameStart(){
while(counter < 30){
randomappearance(otterTop);
randomappearance(otterMiddle);
randomappearance(otterBottom);
counter++;
}
}
void randomappearance(GameObject otter){
if(otter != null){
otter.SetActive(false);
var hInput = Input.GetAxis("Horizontal");
var vInput = Input.GetAxis("Vertical");
int xlocation = Random.Range(1,3);
Vector3 newx = new Vector3(2.5f,hInput,vInput);
System.Threading.Thread.Sleep(Random.Range(0,6)*1000);
if(xlocation == 1){
newx = new Vector3(0f,hInput,vInput);
}
else if(xlocation == 2){
newx = new Vector3(-2f,hInput,vInput);
}
otter.transform.position = newx;
otter.SetActive(true);
}
}
}
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Events;
public class PopupScript : MonoBehaviour
{
[SerializeField] private Image popupImage;
public KeyCode interactKey;
public UnityEvent interactAction;
public bool range = false;
public bool interacted = false;
private void Start(){
if (popupImage != null){
popupImage.gameObject.SetActive(false);
}
}
void Update(){
if(range == true){
if(Input.GetKeyDown(interactKey)){
interactAction.Invoke();
interacted = true;
}
}
}
private void OnTriggerEnter(Collider other){
while(interacted == false){
if (other.CompareTag("Player")){
range = true;
popupImage.gameObject.SetActive(true);
print("Entered");
}
}
}
private void OnTriggerExit(Collider other){
if (other.CompareTag("Player")){
popupImage.gameObject.SetActive(false);
print("Exited");
}
}
}
Okay... That was larger than expected sorry.
Sounds like an infinite loop
The first thing I see that throws a red flag is counter and the possibility that it doesn't reset in time before the next call to the function - have not checked the entire code yet.
System.Threading.Thread.Sleep(Random.Range(0,6)*1000) <- this is called 90 times, it sleeps on average 3 seconds -> game freezes for 4-5 minutes
When does it crash? What's the pattern?
I would use a for, but I havent programmed the counter to go up with a click yet. This is pretty much just a test to see if they move x axis
I thought it was in Milliseconds?
Why would you freeze the main thread anyways😱
Yes it is. 0-5 times 1000 ms = 0-5 seconds
ah okay... what could i put instead?
I basically want it to wait until it changes x axis again
Look up coroutines
At the moment, I can't start my game at all. But when I could it began when I entered the trigger, but I fixed that and now its when I press E
When does the game crash? (the while loop is fine, it'll simply be ignored if the counter is greater than or equal to thirty)
So what function is fired when you press e?
Are there any particular details?
So you've got to be targeting a valid creature?
What about on misses?
When I press E, it sets up the Interact Action, and the Popupimage i have shouldn't be displayed anymore, plus my WhackaMoleGameStart() function should start
Im a little unsure what you mean, which values were quicker?
I do have to go so if you want to create a thread or dm me I can look at this more tomorrow
I haven't coded that in yet, so that shouldn't be a problem
Yeah, np I'll probably experiment a bit more
rather, you don't multiply by fixedeltatime (oh maybe you do outside of that snippet of script)
Hey everyone! Quick question: I'm working on a game with skills that can have various traits like AOE, toggle, aura, instant, delayed, or lingering. I'm trying to figure out the best way to handle these aspects in the game's code without using traditional inheritance since a skill might have only one aspect at a time. Any suggestions or ideas on how to tackle this?
so you're completely dependent on the timestep
Alright, so comment out the thread sleep and see if the problem persists.
I'm not on pc but I remember theres somewhere in my code that I do set the speed = something * 0.02 since FixedDeltaTime is always 0.02 anyways. If this was in update then yea you would have to consider the deltaTime
okay
If the problem goes away, you'll need to find an alternative for delaying other than sleeping the entire thread (likely the main thread at that)
Maybe consider a coroutine or self implement a timer
This has been possibly my main issue too...
My code gets sent automatically to the game- and no errors no.
If you didn't save, it'll be the last working compilation which would be the thread sleep version
now I need to simulate my sudden fps drops just so I can test if my logic works perfectly
save what specifically.
the code or the game
The code, assuming you're testing this from the editor play session.
Alright, just making sure.
dw
Try setting the counter to 30 before the while loop to avoid any random appearance and see if the problem persists - trying to isolate it to the random appearance function.
counter = 30;
while(counter < 30)
{
...
}```
I'm currently trying to use a suggestion from another user in this chat, they said that coroutines would be good? Thoughts?
Unless you're positive the sleeping is what's causing the crash, it'll not help you much - although you'd definitely want to not sleep the main thread.
Doing too much isn't good. Focus on how to undo the crash aka what's causing the crash.
does the EnterPlayMode not loading count as a crash?
No
I can't quite do anything if I can't test it in play mode...
You'll have to remove the thread.sleep everywhere you've used it. My guess is that you have it somewhere that runs at game start
I've only used it once, and in that one function.
you shouldnt use thread.sleep tho
So I'm assuming your game is immediately ending now without the appearance function
if the intention is to not slow the main thread
Disabling that function shouldn't have caused the game to not be launched
Try restarting the editor/computer, using it has possibly locked a thread somewhere
okay, I just reverted all my changes.
I've force quit my editor about 5 times by now...
Yes, that's why restarting the computer might be a good idea
So without thread sleeping, it's still crashing?
you could use coroutines for delaying actions
It's actually my first time hearing about coroutines.
Using thread.sleep is not a good idea
It stuck the whole thread and you cant do anything no matter ui or playing
And you need !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
We're not certain if that function is his only problem but yes.
Is this still crashing?
If so, sleeping isn't the issue.
I'd genuinely love too, but I can't at the moment, im on the tightest scheduele imaginable. My deadline was tommorrow, but they changed it to be in 2 hours.
The only other thing that's questionable would be the lines setting the otter to inactive/active
Give me a moment
No, I still can't run the game
Not being able to run the game isn't related to the changes made thus far
You've got something else going on
I thought so, that's why I've been slightly confused so far
A forum says this, could this be it?
Assuming you're referring to the play button not working and not the e interact key
I mentioned it here ^^
Are you using await?
No im not...
This isn't a programming problem anymore. Try #💻┃unity-talk and make sure to not use that sleep function.
Okay, thank you.. I was actually in that channel before i came here
I probably should have done with from the beginning, but I reset the changes to code I made before it began, I'm going to try to load it up now
Okay, turns out: it was a coding error
I accidently built a forever loop
I can enter again
2nd Update: The game doesn't crash anymore, but my "otters" aren't showing up.
Post your updated !code and link it here
📃 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 think i have an idea as to why they're not showing up
could it be that my function in my other script isnt running?
Avoid guessing by placing logs
The wackamole game will start and immediately finish
if i want to make pseudo-ballistics, where projectile flies with constant speed and changes it's angle every fixedUpdate (until it's angle is vertical), i can calculate distance of straight line trajectory easily and then apply some multiplier to compensate for trajectory's curvature. If i know max distance at which projectile's trajectory will look like halff-circle, how to calculate this multiplier?
Whatever you've got going on after that while loop would be what's to occur thereafter.
Physics projectile motion formula 
The main issue I'm seeing here is that the otters are meant to stay visible even after the end of the program.
any1 know how i can make it back to 2d
idk what i did
nvm
how do i get rid of that
This is the programming channel but it would be this button
mb and thank u i just saw beggginer so i went here
#💻┃unity-talk would be the general non code channel
I think i just found my issue
