#💻┃code-beginner
1 messages · Page 445 of 1
I mean, is that what you're making though? A 2D tile based game?
Yeah, basically
Then really the player should just be "examining" the tile in front of them to see if there's anything on it, and handling the results. You don't necessarily need to do zones or anything.
But again, depends on your game. If you want an NPC to have a (!) above their head when you're near them, that would be a trigger zone, vs another way to detect the player is actually interacting with them
It's not a one size fits all solution, you need to clearly define how you want interactions to work in your game.
I am thinkin only about the interactions with NPCs for now
the ones you need to press a key
when collision boundaries for 2 moving objects controlled by the player are set (where both objects cannot bypass these boundaries)
how can i let a third object bypass the same boundaries?
when you press the key, how do you check you are interacting with some object that has the InteractableComponent?
normally a trigger, overlapsphere (see if ur in vicinity) or raycast
that should be placed on the player, right?
Yes, the player is reponsible for deciding that they've checked for something in front of them
if its raycast u should raycast from the player.. trigger and stuff could be on the interactable object.. but still makes more sense for the player
i cant say for 2d.. osteel might know
You could overlap with any shape. If you want to use that, just make sure it's smaller than the size of a tile, so you're not overlapping two interactions.
To be clear, overlap here means using the OverlapBox / OverlapCircle functions and doing it in code. Not actually using a physical collider.
Collision layers! https://docs.unity3d.com/Manual/LayerBasedCollision.html
Are they better than a boxcollider2D
if using the overlap circle is better than having a child object which is a BoxCollider2D using it as a trigger
Both will work, there is no better
However, if you just have an actual object that is moving with the player, you will have to manage the triggers
If you check with code (overlap box or circle), you can control when you actually care to check, such as once the player finishes moving to the next tile.
ooh okay, this might be way better
I suppose, using Colliders should be more efficient in terms of performance in the majority of cases, than, for example, casting an overlap every frame
Don't confuse this with being "more performant" if that's what you're thinking. There's no need to micro optimize any of this.
okay, ill try overlapbox then
should it be a box thats bigger than the player or one that spawns in front of the player
Actually i need help again... A statemanager is too advanced for me sadly ._.
can someone help me, but dumb it down very very much <-<
Just to clarify, you've got these "markers" with children representing content. When a marker is selected it's content should be shown, and the other markers in their entirety should be disabled, is that correct?
exactly
Have you also considered reading my response?
Excellent 👌. How do you handle the click events?
when you click a marker, the content of that marker should be loaded, all other markers disabled.
OnMouseUpAsButton
I've tried but I think this is still too advanced for me, I was kinda struggling to understand what I'm doing
If there are multiple objects, there may be a need to create a single variable, List, which contains all references to the Buttons, and triggers an event when clicked
private void OnEnable() =>
yourButtons.ForEach(b => b.onClick.AddListener(YourEvent(b)));
What is that you're struggling with here?
Where do i start
By making them UnityEngine.UI.Buttons?
So, I'm struggling with the context. How do i make them buttons? What does the => mean, whats a listener ._.
Yeah that I know
Then why are you asking how to make them buttons?
i just realised how you meant it
i thought there's a way to code them as buttons
but i know what UI Buttons are
as long as u mean these
There is a way to code them as buttons, but Unity already provides a built-in one
There is no graphic
Attach an image too
if I'm adding an image, doesnt it cover everything else? doesnt it make sense to not have them as buttons
i mean to not have them have images
Well, is this paper a single image?
And you don't have it separated by those images?
oaky so
This... is bad
u can just use a square or something.. and overlay them on the image..
this is a bit complexe to explain
Well, you should first consider making this whole photo a UI Image
the image you see is a brochure with AR Elements, you're palcing the AR elements on that brochure so the image has to be loaded
but arent these orange markers, enough?
tehcnically?
i cant, they need to be an ImageTarget
AR_ImageTarget
Can we just see a screenshot of a marker object's inspector? 😅
So you can still do what sashok was describing. The only difference is where your marker object script handles a "click" you'll have it invoke a custom event.
public event Action<MarkerScript> OnClick;
public void OnMouseButtonUp() {
OnClick?.Invoke(this);
}
(or similar)
Then the manager can subscribe to this event
private void OnEnable() {
foreach (MarkerScript marker in Markers) {
marker.OnClick += HandleMarkerClicked
}
}
private void OnDisable() {
foreach (MarkerScript marker in Markers) {
marker.OnClick -= HandleMarkerClicked
}
}
void HandleMarkerClicked(MarkerScript marker) {
// ...
}
You can also do all of this without events at all - give each marker a reference to the manager and have them call the method on the manager directly when "clicked". But the event pattern is a little cleaner, and events are a great tool to have in your toolbox
You can hire someone online for that, but no, this server isn't a place for finding someone to tutor you.
There are lots of beginner resources online for that.
ok sorry for the misunderstanding
i followed the this layerbased collision but it's not working at all, what could be reason?
Almost everyone here learned on their own.
Try thise
https://www.w3schools.com/cs/index.php
And then
https://learn.unity.com/pathways
What does "not working" mean - the "third object" is still colliding when it shouldn't?
Can you share screenshots of the inspectors including the colliders for the "third object" and the boundary. And one of your layer collision matrix?
has this ever been solved.. I have a rigidbody that moves w/ offset from camera.. (camera is attached to CC)
no matter what combination of interpolation or changing around update loops and stuff i can't get all of the jitter out
its better but not perfect 😢
how can I keep objects static while still wanting them to be detected with overlapCircle??
they only need a collider for that
how is the rigidbody object actually moving here
overlap detects colliders not rigidbodies
its tracking my camera + offset
which is child of my CC
w/ physics forces.. 1 sec
what? then I dont know why it doesnt detect it without a Rigidbody
// Apply lift force to counteract gravity
Vector3 lift = direction * liftForce * Time.deltaTime;
pickedObject.linearVelocity = new Vector3(pickedObject.linearVelocity.x, lift.y, pickedObject.linearVelocity.z);
// Clamp the y position to ensure it does not exceed maxHeight
Vector3 clampedPosition = pickedObject.position;
clampedPosition.y = Mathf.Clamp(clampedPosition.y, 0, maxHeight);
pickedObject.position = clampedPosition;
// Update the target position
targetPosition = followPosition;
}```
wait this is in update.. 1 second
imma try late update
I dont know why it isnt detecting anything
- !code 👇
- prefer TryGetComponent over two separate GetComponent calls just for one of them to be a null check
- a rigidbody does not make it any more likely to be found using a physics query, the query will find colliders that don't have a rigidbody justfine
📃 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.
well it only detected the component when using the Rigidbody
1 sec, i'll try fixedupdate now lol..
because you clearly did something wrong. but without any further details we cannot possibly know what you did wrong
share code for ctx, else we're guessing
this tryes to get a component of interaction
yes that was the only part of the code we could actually confirm the validity of
and then start a method which is in that component of other gameobject
which uses a UnityEvent
show 👏 the 👏 code 👏
i give up, fixedupdate looks jittery too
guess i'll just not use a lift mechanic on my CC.. i'll instead reserve it for my Kinematic boi
have you actually done anything to find out what was hit? because you aren't filtering any colliders out of the OverlapCircle which means if the overlapcircle finds literally anything else first then it has failed to find the Interactable object.
so i'd bet that it's not that it isn't working without a rigidbody, i'd bet that the rigidbody is just making it a higher priority so it isn't finding other objects first. you likely just need a layermask to ensure you are only detecting interactable objects with that query
Okay, lets try that
you're also doing literally nothing at all to ensure you are only calling TryGetComponent when anything was detected, so if nothing is detected you'll be receiving NullReferenceExceptions, and if you are not then the issue is 1000% what i said before
making progress 🫠
@raw token little did u know.. but ur reactions were motivating me! 🙂 🙂
whoop whoop! hell ya
just needed some fine-tuning of the forces
MUCH higher forces than i expected
and hella dampening to accompany it
and i changed the tracking to use RB.MovePos in fixedupdate @slender nymph so thanks for that too
Epic!! I've been invested because I often run into jittering and I've never wholly wrapped my head around the causes 🙃
fine-tuning is the key
and using fixedupdate/lateupdate
im happy to share the code w/ u if u wish
ah i was actually just about to suggest swapping to moving it via MovePosition since you were just assigning velocity and that wouldn't give realistic interactions with outside forces anyway
mmhmm. i just needed to let go.. and let the physics engine do its thang
but it looked rough.. so i figured it was the logic.. but no it was just the values..
Yes please :)
I'm not sure when I'll next be doing something to which it's relevant, but I'd love to study it a bit, and keep it in my back pocket
i'll probably need to keep all my pickupable objects around the same mass to keep it consistent
https://pastebin.com/f7cwMuX7 here ya go
Thank you! 😁
the rb and the values i used
phew, that was actually on my bucket list 🤣
another one bites the dust
who's next 😈
Is it bad practice to use a static rather than constructor or does it depend on the scope of what you're trying to do?
that's so vague . . .
This question is like "Is it bad practice to use a broom rather than a television?"
@bold plover can you clarify?
you mean to call a static method (to create an instance) instead of that type's constructor?
Hello I am new and would like to create a VR app with hands that are detect through the camera for a project. Can you tell me how I could do and/or the steps to follow.Thanks
It worked! thanks
Of course! Error CS0120. Trying to make it so that movement values in the main player script correlate with movement state. Wondering if it is better to declare that variable as static or define that object as part of a constructor argument.
Hoping that makes a bit more sense.
first and foremost, always start by saying what you want to achieve and what is happening instead. always provide error messages for context . . .
Alright. I wasn't certain if it was worth it as there are two listed solutions. I'm just not sure if one is "better" than the other.
on top of this, you also cannot use non-static variables in a field initializer so that wouldn't have been valid even with an instance reference
How do I log positions? And detect if an object has gone past a certain position?
Debug.Log
Just debug and transform.position?
Debug.Log($"My position is {transform.position}");
Ahh ok
you can log whataver information you want, yes
log the value(s) you want to track. that's up to you . . .
Figured, just hadn’t done much with the position information in code, that was the main part I was wondering about, but if it’s just transform.position that’s pretty easy
transform.position is the position of the object, yes
Also meant moreso like
Logging it to a variable, or something I can check for another object
the beauty of programming is everything is data
and you can do anything you want with it
Like if object A is past object Bs Y position then do this
Heard. I think I understand a bit better now.
sure, just comapre them with the comparison operators
if (a < b) etc
Been spending the last two days just reading about constructors and trying to get all the details under my belt.
Do I need to make them GameObject Classes? Or can I just search the scene for objects?
i have no idea what that question means
in this example a and b are numerical values
To compare 2 objects
you don't compare objects
At least I hope I understand said point as you intended, haha.
you want to compare their positions
Cuz I need their individual transforms to compare
Yeah I have to reference them somehow
you need references to the objects to get their positions, if that's what you're asking
is there a way to initialize a sprite to a source from code?
public Sprite sprite = new Sprite
What do you want this sprite to be? From an image?
Certainly not in a field initializer like that. But in general, yes. What's the goal?
I guess so, when I drag an image in there it just shows a sprite
What else are you expecting it to show
So, you want a variable you can drag in image into? Just make a variable of type Sprite
I was hoping to initialize it from code as it's in an array of them
to avoid having to drag alot
you say from code but... from where?
So, you want a variable you can drag several images into? Just make a variable of type Sprite[]
you can select a bunch at once and drag them all into the array.
they are subelements of other arrays, so can't just drag a bunch like that
then sure, just populate an array in code. You certainly wouldn't be doing that in a field initializer though
ever heard of a for loop?
hi this script is for a 3s countdown. in game it shows 3,1 and not 3,2,1 as it should i also tried it with higher countdowns and it skips for 2 numbers there too like for 6 : 6,4,2 ``` cs
public class ReviveScreen : MonoBehaviour
{
public GameLogic logic;
public Text CountdownText;
public int Countdown;
public void StartCountdown()
{
StartCoroutine(CountdownS());
}
IEnumerator CountdownS()
{
while (Countdown > 0)
{
CountdownText.text = Countdown.ToString();
yield return new WaitForSeconds(1f);
Countdown--;
}
yield return new WaitForSeconds(1f);
logic.CountdownFin();
}
}
Countdown is public. Something else could be changing it, or you could be calling StartCountdown more than once
Also if you really want 3s use WaitForSecondsRealTime
yeah i have it in the logic script to call it and start it
Show that
Sure. !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.
cs
public void RevContinue()
{
pipeGen.SetActive(false);
GameOverScreen.SetActive(false);
revScreen.SetActive(true);
BackMusic.UnPause();
revive.StartCountdown();
}
}
message was too lng
Debug.Log to see where and when the Countdown--; part is running
Man if only the bot message I just called up had a section for posting code blocks that are large
Also I have a question for you - why is Countdown a public int member variable? Why can't it just be a local variable inside the coroutine?
because im new
also
i debuglogged the countdown it showed what its supposed to show on screen 3,2,1,0
where
where did you put the log
and when did it print
look at the timing of when it prints. Is it printing two numbers at once, then waiting 1s, then printing two numbers again?
It's pretty clear you're calling the coroutine twice. That's why I asked for the code of where you're calling it
I would just guess RevContinue is running twice basically
yeah it goes two numbers at a time
OKay locking y works, but my object tends to rotate in the environment i have, and it wont rotate back.
I should probably just get rid of object rotation all together.
The objects will be big .
!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
since the vscode editor extension in unity isn't supported anymore, can i just use the vs editor extension, even though i use vscode
VSCode is now supported through the VS Editor unity package 👍
if you mean the VS Editor Package, yes you have to use that also for VS Code
the configuration guide linked by the bot even specifies you use the Visual Studio Editor Package rather than the legacy Visual Studio Code Editor package
do i need to press regenerate project files tok eep visual studio code from defaulting back to code cmd every time i reopen unity?
if that happens every time you restart unity, it typically means that unity was unable to write that setting to the registry for whatever reason. launch the editor as administrator, change the setting, then launch it without admin privs again and it should stick
thanks'
it does indeed work, ive used this exact solution before
What aboout collisions? My objects go through other ones.
mine do too if i force them too far.. i havent figured out a solution to that yet
probably a max distance from the anchor point
Oh ok, so it isnt just me.
It does snap outside of the other object when i let go of it, so i may have to just leave it in.
oh.........
Are you setting yours kinematic?
That may be my issue.
How could I program that teh damage that the players deals to a tree is bigger with an axe than with a shovel for example
i shared my code up above.. if u wanna check it out #💻┃code-beginner message
Oh my god, thank you that worked.
you have a generic damage function.. that takes in an int or a float for example.. and just pass that to the tree..
DealDamageToTree(int amount){
tree.Damage(amount);
}```
then every weapon/tool would just have a damage amount to use
yeah but how can I distinguish the damage it deals depending on the type of tool
not sure how its set up.. but u could use 1 tool script that has a damage variable u can change.. and u can assign that to all ur tools
just changing that damage amount
but I dont want the tool to deal that damage to every single object, for example, an axe should break a tree easily but a shovel no
could use an enum for ur tools
float CalculateDamage(ToolType toolType)
{
switch (toolType)
{
case ToolType.Axe:
return axeDamageAmount;
case ToolType.Shovel:
return shovelDamageAmount;
default:
return baseDamage;
}
}```
public void TakeDamage(ToolType toolType)
{
float finalDamage = CalculateDamage(toolType);
Health -= finalDamage;
}
``` and im not sure what u mean by u dont want everything to be damaged.. u'd only have scripts on the things u want damaged..
the enum would look like
public enum ToolType
{
Axe,
Shovel,
etc,
}```
np, theres dozen other ways to do it. but thats what came to mind first.. since ur talkin about multiple tools
And should I have a component for every structure? treeComponent, rockcomponent, mineralcomponent?
hmm, actually id have to think about it..
thats actually a bit more complicated than originally thought
multiple tools and multiple structures.. 🤔
the clearest reference is minecraft
interfaces come to mind.. IDamageable.. (all it knows is that it can be damaged) and every thing u inherit from it could just have a Damage() function you call..
you'd still need different components.. but the logic would all be the same.. so u'd just have to check which tool is being used
public class Tree : MonoBehaviour, IDamageable
public class Wall : MonoBeahviour, IDamageable
etc
wait does I stand for interface
that could be indeed
"Interface"
like the I in Ienumerator stands for interface?
hmm, lol idk
yes
ah, finally i get what it means
Interface naming goes like I<PascalCaseClassName>
I wish Unity respected the full convention
especially on fields and properties
It is convention to add an I to the start of all interfaces.
unity does respect that
unity uses camelCase for fields no matter what
camel case vs PascalCase ?
While the convention is PascalCase for public fields and properties
camelCase PascalCase
You do see that clash when you use anything not Unity specific
i see
i.e a library or something in System
which would be horendous
Transform Transform
anyone?
love it
I want to add an external outline but setting tmpro.outlineWidth gives me what's in the second image
I use pascal for mutators :P
Consistency would be preferable
They unfortunately do not. There are multiple libraries with differing conventions
Honestly all the libs i've used till now that aren't made for Unity follow the convention
Tho i haven't used a ton
To be clear, I meant Unity libraries
Like internally, unity is not consistent
if my ide didn't handle references so well, id probably bea little more critical about my naming
but its all over the place at times
I bet they didn't bother because they used UnityScript before...
It's mostly because they acquire things and just mash them in
They call it Javascript but it isn't, the interpretter of that thing was even made in Boo, which apparently was another .NET language they supported before
ages ago
never got a chance to try out Boo.. lol always wanted to since I heard tha name 😄
Who called it Javascript?
Laugh at them
ooh boi
if i > 0:
print "i is greater than 0."
if i < 10:
print "i is less than 10."
if i > 5:
print "i is greater than 5."
// Output: i is greater than 0.
// i is less than 10.```
noice
I hate it lol
same, along w/ python
Only reason i hate python is the indentation being relevant to the code
that and snake_case
And it breaking all the time
Woah woah woah....
Rust uses snake_case
Like it's the only language that can work on my machine a moment then break the next without me doing anything
I legit made a thing for a class and saved it on github
2 days later i run it and it doesn't work anymore
Or that one time it broke during class
where i double checked it working 2 minutes ago
Youd be surprised how many people say that, only to realize it was always their fault
It either:
-Was always bugged and you never noticed
-or you changed something and didnt notice. Meaning you need version control
computers never be doing what u tell it to do.. just stubborn
you know what they say, 'You can NEVER run the same program twice'
#skynet
Done it, trivial and pointless
How do I put my code in here for people to read?
!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.
void SetMovementSpeed()
{
if(Input.GetKey(runKey))
{
walkSpeed = Mathf.Lerp(movementSpeed, runSpeed, Time.deltaTime * runBuildUpSpeed);
}
else
{
walkSpeed = Mathf.Lerp(movementSpeed, walkSpeed, Time.deltaTime * runBuildUpSpeed);
}
}
Can someone tell me why when I let go of shift, my character doesnt slow down to the walk speed?
It starts as the walking speed, when i hit shift it goes up but dont go back down
because you have already changed walkspeed to runspeed
Right but the else should change it back when i let go of teh button
how? where would it get the original valie of walkspeed from?
You should probably have it return an in instead.
How do I do that?
Or float or whatever walkspeed is
it's simple dont use walkspeed here
walkSpeed =
It will be both more readable and easier to debug.
So just only have one float as the slower movement speed?
also, that is not how to use Lerp
How should I use it then?
lerp takes a t value between 0 and 1, see pinned messages for correct use
can I make a private inner jump class and then a separate public jump class?
You can make as many Jump classes as you want as long as they're declared in a different scope
Theoretically yes but it may not be a good practice.
Depending on what you are doing exactly
where can i put a lot of code? like a website like pastebin for coe
📃 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.
!code
ty
Problem:
https://gdl.space/erifegufuc.bash
The issue is in in the top of the paste.
Feel free to ask me more and also if it's a bad thing if I'm pasting all my scripts.
you kinda fucked it by adding your stuff at the beginning 😂
we dont know the line numbers now
By including your question in the paste you've made all of the line numbers in the error worthless
oh shit
mb lemme fix that
post each script separately as well
okie dokie
only post the relevant scripts too, not every single one that we dont need
alright
the reason why is because they use classes from other scripts. the scripts i will be providing might not be of any use, but im not sure what the problem totally is so im just including everything that is needed for the main script to function
links to every script
line numbers accurate
What is with this obsession with containing the entire message in a single bin
Initial Question - https://gdl.space/zewilekoza.sql
InventoryManager.cs - https://gdl.space/wawuhogive.cs
InventoryData.cs - https://gdl.space/gufaxiguve.cs
ItemDatabase.cs - https://gdl.space/vusexixoza.cpp
ItemSO.cs - https://gdl.space/yeyokoveko.cs
InventorySlot.cs - https://gdl.space/debidufali.cs
EquipManager.cs - https://gdl.space/ocevolepik.cs
nah i cant
ok sorry
oh i see, i think your trying to "unequip" the item?
yes
hence the null?
just make another method for unequiping and pass the slot or whatever you need
instead of giving it null
ok let me try that
or well you could do it here
since you have an if statement for if its null
just dont error it and make it actually unequip, or make another method for simpleness
ill just make another method
my unity crashed 😭
are dynamic methods automatically checked in c#?
also just for future.
the error was for line 70, line 70 says you pass null
simple error simple solution
not sure if you actually did read the error and stuff but who knows 🤷♂️
i read the error but i didnt think of scrolling down over there lol
when i double clicked it
it just brought me to
{
Debug.LogError("ItemSO passed to EquipItem is null.");
return;
}```
so i thought the item wasnt actually functioning
You can click the error message and read the detailed log below for the full stack trace
and this is part of EquipItem which comes from the other script, which shows on the next line of the error
that other script AT line 70
oh i didnt know that
most null errors are easy to solve
good to know
does c# have something similar to javadoc comments?
do you mean /* stuff */?
Javadoc comments automatically generate documentation based on format, not sure if that's what he wants
yeah thats what I want
is it bad practice to use dynamic methods? Anything I should be doing in terms of exception handling or something?
There's no in built solution that generates something based off the XMLDocs it seems
Thank you for looking for me
Was curious myself, no problem.
anyone know if this is changable in unity, I want to add a fading out object.
I saw a 'clear' static property although I don't want it to be instantly changed but faded.
you can change it
color.a
Hello, I just started Unity and even though I wrote the same code as the man in the video, my codes gave an error and I couldn't figure out exactly why.
I'll give it a try
you didnt do the input system stuff i think, or thats an old video
OnFoot Onfoot onFoot
unless your not supposed to, maybe remove the s?
whats the video showing
I was following the steps of the guy in this video and I encountered this error
I would imagine it's supposed to be an input action map
the code doesnt matter
apart from 1 upper case instead of lower case in OnFoot
show his input map
while(color.a > 0){
timer += Time.deltaTime;
if (fadeTimer <= timer){
Debug.Log("yuck");
color.a -= .1f;
timer = 0;
}
}
if (color.a <= 0){
Destroy(gameObject);
}
}```
anyone know why this script is instantly removing the platform instead of fading it out
(the fadetimer is a float and set to .25f)
you should use a coroutine or a tween ideally
because it's not a Coroutine
I'll try using a coroutine
it loops until it's done, all at once
is C# object keyword "Object" or "object"
object
ty
Stop calling GameObjects “objects” in confuses me 😭
I don't want it to be all at once though, I want to make it fade out over time.
GameObjects are not objects
kinda
everything in c# is an object essentially
You need to wait for the end of the frame while looping
you are in a OOP(object oriented programming) language
thats what coroutine does
Then use a Coroutine
oh
without coroutine you would have to take out the while loop and only use time.deltaTime / timer
They inherit from Unity Objects.
Which is different from c# object iirc
yes but that Object is specifc to UnityEngine.Object
Does anyone know how I could return the text property of a TMP component as a string array to be iterated over?
I should've been more clear, everything is basically an object
not specific to GameObject though i meant
you make a class, thats an object (a blueprint to one actually)
Yeah. Language for objects is kinda confusing since some beginners since I see some call GameObjects objects.
they only do that because its shorter and quicker to write, and everyone still understands what they mean
string.Split?
string are already arrays of characters
let me just show you my code maybe it'll explain itself better
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class TextScroll : MonoBehaviour
{
private string[] text;
private float textSpeed = 0.01f;
private TextMeshProUGUI textTMP;
private int index = 0;
void OnEnable()
{
textTMP = GetComponent<TextMeshProUGUI>();
text = textTMP.text;
textSpeed = GlobalVariables.textSpeed;
ActivateText();
}
public void ActivateText()
{
StartCoroutine(AnimateText());
}
IEnumerator AnimateText()
{
for (int i = 0; i < text[index].Length + 1; i++)
{
textTMP.text = text[index].Substring(0, i);
yield return new WaitForSeconds(textSpeed);
}
}
}
The intention is the script gets the TMP component of the GameObject, it loads up the text (I need it to be as an array type though I guess somehow), and it then iterates over the text for each character until the coroutine is done
but this current setup returns a null object reference
which line
are you doing some type of typewriter effect or whatever
text = textTMP.text; it says it cannot implicitly convert from a string to a string array string[]
exactly that
Because a string array is not a string
yes because strings are not array of strings
What are you trying to set text to? Which strings?
text is supposed to be the text contents of the TMP object
if you want to iterate over the chars just iterate over the string, its already an array
Okay, so why is it of type string[]
string.Join
But why did you make it an array?
are you just gonna name every method linked to string? 😂
Oh wait misread sorry. 😅
that's just how the concept was set up by someone else and so it seemed like it needed to be an array to be iterated over by its index but I guess it being a string in general would allow that wouldn't it
I'll try some things
dont just expect that "someone else" did something correctly, try to understand it yourself also
yes. Like I said, string is already an array of chars
There was an attempt
It's saying there's no substring method because it's per character
I believe you can also just use the property maxVisibleCharacters instead
[SerializeField] float fadeTimer = .25f;
void Start(){
color = GetComponent<SpriteRenderer>().color;
}
void OnTriggerEnter2D(Collider2D coll){
if (coll.name == "Player"){
StartCoroutine(Fade());
}
}
IEnumerator Fade(){
color.a = color.a - 0.1f;
yield return new WaitForSeconds(fadeTimer);
}```
I'm kinda lost in why this script isn't doing anything (I'm trying to make an object fade out if a player touches it)
your running it literally once, you need to loop it
You're just editing a Color field, not actually changing the SpriteRenderer color
oh damn
🤯
not sure why i never realized that Neat!
the difference is they are Immutable so you cannot replace chars by index
reason why new strings needs to be made when modified
ahh gotcha gotcha makes sense..
I think tmpro has a max visible characters field you can use instead of this also
ohh epic
i see caesar also mentioned that.. ❤️
Oh my bad, I didnt see that
me neither..
but im changin it aorund right now..
im all about TMP functionallity
Alright so I reworked it slightly and well it does work but it seems like the coroutine only iterates about 14 times and then just stops before the end of the text's length
actually it varies
how??
I have no idea
Show updated !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
if u use the same string each time, im not sure how it would ever vary lol the loop is the same
I'll show you the in-game result of what I mean
it only runs for so long and depending on the textspeed it stops early
Okay, so, add this log inside the loop:
Debug.Log($"{i} / {text.Length} - {text.Substring(0, i)} / {text}");
And show what it logs
Will do
For some reason it just works as intended now after I decided to log it
before it would stop before the end of the string
now it finishes
no change
I think it just hates me ngl
but thank you guys
for the solutions but also the patience
i want to make a drop down list for a dictionary, how do i achieve that?
https://www.youtube.com/watch?v=x-ejym1WdjE
oh nvm i found this video ty
In this tutorial we will see how to serialize a dictionary or anything else that you can't usually serialize and make it show in the inspector of your unity project to help you improve the process of making and developing games.
#unityin60sec
Come hang out on Discord
https://discord.gg/sZmAkFXeRT
what project
@floral vale There's no collab/job postings here. Use Unity Discussions.
i want to have a Door object, and also a button in the inspector to set it's spawn location. how can i achieve that?
How do i get a variable from another skript. I looked so much online and can't find a solution
get a reference to an instance of the object with the public variable you want to access. then use the . operator to access it
Idk about making it a button but my solution was to serialize a string and have it be the name of a scene
might be a little bit hacky because obviously scene names can change but that is one way to do it
try
ScriptName varName = gameObject.GetComponent<ScriptName>
then to access the variable,
varName.variable
i already serialized the list of the scenes so its easy, but the next step is to set which door does it come from and which coordinate it spawns when the scene loads
the gameObject part is redundant
Well, that brings in another system I made then which is for setting the spawn position in a scene
basically I made a series of empty GameObjects and loaded up references to each in a script in every scene, and that script then switches based on an integer, and the integer determines which gameobject to transform the playercapsule to** **
depending on how you want to do it you can set the spawn position either as a value the function returns or maybe store it globally
is there a way to find out where the input axis is coming from? I have no peripherals plugged in beyond keyboard/mouse/headphones and for some reason my input axis is reporting .17 on the vertical scale.
ah, restarted unity, it fixed it.... never mind thank you
programming at its finest 🐦⬛
yeah, i did that, but then i thought i wanna torture myself and make it more convenient to create a spawn object by pressing a button of each door
This is a really crappy way to serialize dictionaries
i watched the video and yes, i thought abt that, so i just look for a lesser way to do doors and spawn locations 😔
You should have a class that extend dictionary for serialization.
Or buy odin inspector if you don’t want to write your own.
Wait, are you doing lookups?
If not you can make a list
https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html
could even just use this
but there are other better implementations online out there
Yeah. Make a struct list of KeyValue pairs that adjust serialization
[System.Serializable]
private struct DoorSpawnLocation
{
public Vector3 spawnLocation;
public Door spawnedDoor;
}
[SerializeFeild]
private List<DoorSpawnLocation> doorSpawns = new();
@jaunty bay if you are not doing lookup values just do this.
for some reason my movement code is snapping me to 0,0,0 - I have tried setting movement speed to 1 in the actual function and its still being funky.
{
// if we are holding a movement button, we want to move in that direction
MovementSpeed = 1f;
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 location = transform.position + new Vector3(horizontal, 0f, vertical);
rigidBody.MovePosition(location * MovementSpeed * Time.deltaTime);
}```
both my horizontal and vertical axis are correctly 0 when this happens, too, I made sure of it
so with 0 it should just be moving me to my current location
instead I snap to 0,0,0
You're constantly multiplying your whole position by delta time
OH!!!
If anything, you should be only multiplying the position change
I refuse to use third party tools for anything!
(but seriously thank you, obvious in retrospect for sure!!)
You shouldn’t.
Especially as an indie developer.
Plus, Desmos is a website. You aren’t installing anything into unity
how i convert valuecollection to list/array
you don't use a calculator irl because its third party made?
.ToList()
But think about a way you don’t need to do that
Does anyone have a good tutorial for adding bullet holes to walls when I use my gun?
i wanted convert it to json
and a tutorial for adding trails when shooting
but then i realized arrays dont work at all
use decals. you can use
to find a relevant tutorial
what about particles?
cause im feelng like decals might not work in some scenarios (i.e. on players)
I want at least a particle where I am shooting
well last time i checked a player is not a "wall" which is what you had actually asked about. but yes, you can use particles for blood effects and the like to show you've hit a player. none of this is really code related though
hmm got u
also one more thing, how would I go about adding trails to my hitscan gun?
imagine it was this easy..
I followed that one tut at the top
it doesn't show a lot of thing
like how they got the material for the hitscan
thats something you should learn before making hitscan weapons or any
!learn has good pathways to learn such essentials like making a material etc
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
if u come across something like that.. look at what component they're using.. then search that specific thing.. figure it out.. and then return to the tutorial
not all tutorials are going to cover every single step
i mean the trail
mb
aight thanks ig
"trail material unity"
its all there btw.. if he doesn't change the material its using the default material
he does have a different material, becuase the trail has orange
ah yea ur right
prob its some type of emissive material
looks like its something like this
learn a bit about gimp/image editors so u can make things urself
it helps out alot when u cant find things u want
if i want to use one material for when damaged and another material for on death, do I have to essentially have two spriterenderers for each situation and set them active/inactive?
or u could swap out the sprite in the renderer..
youre right, just found out how to swap the material. thanks
I'm having an issue with the way transform.TransformPoint() is working. If I pass it a vector that I have confirmed is (-.9, 0, -.9) then it should return a Vector3 that is in the world location of a point that is (-.9, 0, -.9) in the local transform space. However, that's not what I'm getting.
Here is my code:
Debug.Log("Vertices[0] * .9f = " + Vertices[0] * .9f);
Debug.Log(transform.TransformPoint(Vertices[0] * .9f);
If I take the outputs of those logs, create two empties, one at (-.9, 0, -.9) in local space, and the other at the point output by transform.TransformPoint((-.9, 0, -.9)) They are not in the same place. I have confirmed that transform is referring to the correct object. What am I missing here?
I need help guys
This is my code and its providing this error
does anyone knows how to fix it
Remove system.numerics at the top
ok
thank you
What is it outputting instead?
Why do all beginners call their rigid body variables rb?
I have almost a decade and I call mine rb
Okay. Why?
Why not? Why ask? Why care?
It is easily recognized, and common
What do you call it?
steve
- You don’t want to use it due to it a non descriptive variable name.
- I don’t know where it game from, and I am curious.
- I don’t. Beginners fall under bad practices all the time and critiquing them can be discouraging. However it is such a weird pattern that I much know.
I rarely use them. I would call them rigidBody or something similar.
- i strongly disagree
- it is just intuitive and obvious. It is immediately obvious what it means (which is why I disagree with 1)
- i have no idea why it would be seen as weird.
You would capitalize halfway through the word?
Rigidbody is one word. I would definitely find that odd
But yeah rigidbody is fine 🤷♂️
I normally use full words for almost everything. But.... i mean this is a rigidbody. It is like shortening camera to cam. You know what it is
I don’t use em’ like I said. Unity learn does it though.
The results are close, but a few tenths of a unit apart. It seems dependent on the orientation of the parent of the transform object. I think I'll have to do some more testing. I just wanted to make sure I wasn't misunderstanding what it was SUPPOSED to be doing.
Oh. That is just a natural byproduct of float math
Float math isn’t 100% precise.
You mean it's going to be off by like .3? That seems like absurd margin for error.
Oh .3? Never mind then. I thought it was something like 0.0003.
No, tenths. Yeah idk. I think I can figure it out tomorrow. But geez it had me stumped tonight.
I have a feeling it is some other force at play then the transformPoint method. Good luck though
can I use decals in the default render pipeline?
what did your google search reveal the answer to be?
it seems to be no
it seems to be that you didn't bother actually verifying then
first result googling "unity decals built in render pipeline"
https://docs.unity3d.com/Manual/visual-effects-decals.html
huh no idea unity had a similair component in birp. always used a zbuffer shader thing
TIL
also do you reccomend me sticking with the built in render pipline or URP?
that entirely depends on your needs
I actually found a hilarious video that perfectly demonstrates why you shouldn't use Chat GPT for coding 🤣
Should be added to the FAQ or something: https://www.youtube.com/watch?v=rSCNW1OCk_M
Anarchy Chess Post: http://bit.ly/3jLT4JZ
➡️ ️Get My Chess Courses: https://www.chessly.com/
➡️ Get my best-selling chess book: https://geni.us/gothamchess
➡️ My book in the UK and Europe: https://bit.ly/3qFqSf7
➡️ Mein Buch auf Deutsch: https://bit.ly/45fKt3R
➡️ Mi libro en Español: https://bit.ly/3Y5xaRx
➡️ Mon livre en français: https://bi...
i'm trying to do dependency injection like this but i'm really confused
https://unity.huh.how/references/simple-dependency-injection
i have a parent object instantiating a child object
but i got this error
Assets/Permutor/ManagePermutor.cs(68,20): error CS1061: 'GameObject' does not contain a definition for 'Init' and no accessible extension method 'Init' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)
you've already been instructed on how to resolve that error. show what you tried
also notice that the examples on that page do not use GameObject variables for either the prefab nor the instantiated instance
var isnt the issue
the type you picked for prefab passing in instantiate is what matters
public class ManagePermutor : MonoBehaviour
{
public PermutorHandle handlePrefab;
...
PermutorHandle handle = Instantiate(handlePrefab, Vector3.zero, Quaternion.identity);
handle.transform.SetParent(empty.transform, false);
handle.Initialise();
}
other file...
public class PermutorHandle : MonoBehaviour
{
public void Initialise() {
}
}
i got
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)```
not sure thats from that code is it?
maybe not
well that isn't a compile error, so maybe provide literally any info about what caused the error
let me clear the logs
oh my god it worked
ok i gotta add parameters now
to Initialise()
science
ye i was hasty posting that error
sorry
wow ok so you drag the prefab to the inspector, but it actually grabs the class defined in the prefab's script
yes
how would I turn on/off the emmission of a particle?
that makes a lot of sense now because i was like how tf do you see other classes
through script obv
The API is right here
https://docs.unity3d.com/ScriptReference/ParticleSystem.html
something is wrong with this nav mesh terrain, it has 4 problems, can someone help me?
Sounds like version comparability issue.
What to do about it?
if (Input.GetKeyDown(KeyCode.Tilde))
Am I missing something here? Doesn't seem to work when I press the key next to the "1"
tilde is the ~ character which requires holding shift. are you sure you don't want the backquote ` instead?
ok that worked, tried holding shift too but tilde still didn't respond
do you have Use Physical Keys enabled in the input manager settings?
seems so yes
well that would be why then. always be sure to check the docs when something isn't working
https://docs.unity3d.com/ScriptReference/KeyCode.Tilde.html
Deprecated if "Use Physical Keys" is enabled in Input Manager settings, use KeyCode.BackQuote instead.
haha thanks, what an obscure thing to happen
For some reason, this wont work.
The whole purpoe of the code is if the player touched an enemy while having the powerup, it'll fling them away.
It detects the powerups and it changes the boolean value, but doesn't trigger the other if statement for the enemy touching the player
https://streamable.com/bkk29a
@deep yew my friend it wont work , because it must be "OnCollisionEnter" not "OncollisionEnter"
Am I doing something wrong guy because my GameManager doesn't change to the gear icon
Is it acceptable to use underscores in clas names?
I was wondering if ICommand and Command_Undo would be better than UndoCommand in terms of readability

It no longer does that in newer editor versions.
its okay to choose any way of writing classes and vars but just make sure to keep using it in the whole project
and "ICommand" is prefered in interface not in normal classes
Oh, tysm
Cops aren't going to come to get you if you do that but then you have a mix of PascalCase classes from C# and Unity and plugins and your own Snake_Case classes which I would say makes it less readable
I Ssssee🐍
Pascal it is
ty
oh ok thank
cannot convert UnityEngine.Quaternion to UnityEngine.Vector3
is there a way to fix this?
@errant solar use quaternion slerp for lerping rotation https://docs.unity3d.com/ScriptReference/Quaternion.Slerp.html
and use quaternion Euler instead of new vector3 , https://docs.unity3d.com/ScriptReference/Quaternion.Euler.html
@errant solar i think you need to go watch and understand more about rotations in unity , and not just take my answer and move on
Vector3 for positions and quaternions for rotation?
Quaternions are a system of rotation that allowed for smooth incremental rotations in objects. In this video, you'll learn about the quaternion system used in Unity and will explore a few of the methods that allow you to work with it!
Learn more: https://on.unity.com/2YniWhk
yes they are 2 different data types , same like an int and string
انت عربي
arabic?
yes
مشكور على الشرح ما تقصر ❤️
ما مفي مشاكل , اي وقت يا اخوي 
ايش w دي؟
its complicated to explain quaternion in few words , and we dont change quaternion directly , we use Quaternion.Euler
so its simple for us to change angles in X Y Z without the W
This is gonna sound stupid, but is there a way to make sure that any scene that is loaded; automatically loads a script even if its not there?
Like say I had a game manager script, that needs to be in every scene; is there a way to tell Unity to automatically load a specific script with a scene?
what is TABLE_ ?
u mean a prefix of "TABLE_"
interestn
ive never done anything like that but im sure its possible w/ someting other than a tryget
u could get all and loop thru checking the name w/ strings
u should use interfaces intsed
if(hit.collider.transform.TryGetComponent(out IInteractable interactable))
{
cachedInteractable = hit.collider.gameObject;
if(Input.GetKeyDown(interactKey))
{
interactable.Interact();
}
}```
yessir
soo things like my Pickup scripts are found w/ that interface
and everything interactable just has an Interact function we call
regardless if its a pickup, a switch, or w/e else
yes, thats what u can do w/ interfaces.. u havee 1 basic interactable interface or w/e
and u can inherit it from different classes (these can be different functionallity for different things)
or u could go the ez route and use a Tag
Table object or something.. and tag all ur things w/ Table..and u could check for that tag w/ the hit info
a switch statement would be a bit cleaner.. but yea interfaces sound like a better solution for what ur talkin about
thanks..
good luck.. come back if u run into any issues 👍
Hi, Im trying to create a grid with some simple pixel art, but as you can see the lines touching is always 2 pixel wide while the side lines are 1 pixel, how should I go about fixing this and have some consistent boarder lines?
Any idea on why this thing is giving me an error?
because you donrt have a class called Enemy
also FindObjectOfType does NOT return an array so there will be no Length property
I was watching a totorial about that, he said that it returns an array for some reason
that is why you should ALWAYS refer to the docs because most tutorials are crap
Got a link to 1 of them?
ight
its own script
it's an (incomplete) namespace declaration
for some one who just reccommended someone else to google the docs, you seem to do very little of that yourself
do you know what
using UnityEngine;
in your code actually means?
its really not important.. its someones custom namespace..
like here.. my IInteractable is wrapped in my SPWN namespace.. if i remove the using statement i cant access it
i could very well not put it in a namespace tho
hey guys.
im trying to remove ALL triangles inside of a collision mesh, that have a normal similar to a normal vector returned by a raycast hit, in runtime.
is there a way for me to do that?
- raycast to get normal
- access mesh data
- calculate normals of each triangle in mesh
- compare normals
- remove triangles
- update mesh
now as for the nitty gritty of that process, no clue
how do i remove the triangles?
because as soon as i remove a triangle the triangle list of the mesh changes and all of the indexes will be messed up
after u remove triangles u have to recalculate / rebuild the mesh
you shouldn't be directly modifying the triangles either..
need to create a new list of triangles and then iterate thru that afterwards to rebuild it
but ive never done this.. soo this is just speculation
alr ill try, thanks 👍
can you check the line of code that cause the program error in unity?
double click the error and it should open up to the line that causes it
theres also (character number, line number) at the end usually
thats not from your code
looks like some sort of unity error/bug
id just clear it out and go on my day
the top one is tho
im trying to make my character move but i couldn't
this is a code channel so share your !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:
- your code
- your setup (inspector windows of character controller, rigidbody, etc)
right, so you completely ignored the bot message
!ide configure ur 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
see anything wrong here?
yes
ur IDE should have it underlined in red
how can i make it do that?
the bot message directly above us.. ^
click the link to the software ur using and follow the instructions (carefully)
when people show you bot messages YOU are suppoed to read them
How to spawn object dynamicly?
Instantiate ? Define 'dynamically'
Basicly I tried to make Highscore in a list and I want to spawn Text mesh pro dynamicly
in a canvas
some how i followed it and it got even worse
yesterday it was just fine did i mess up something?
nope, thats all the errors u didn't see before..
but I still stuck in trying to get my textmeshpro in my gameobject
And STILL not posting code correctly despite being told multiple times
my code looked like this
not gonna work, make a prefab of the TMP object you want and instantiate that
using UnityEngine;
public class Movement : MonoBehaviour
{
public float speed;
private float Move;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
Move = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(Move * speed, rb.velocity.y);
}
}``` the only time im going to do this.. this is the valid code for what ur trying to do.. look over it and compare it to urs..
you are missing a `{` for the beginning of the class, its `Rigidbody2D` not `2d`, its `Input` not `input` and ur missing a ending `}` for the class
Okay ill try
OHHHHHHH i see now
thx
you forgot an opening bracket behind MonoBehaviour
ah you already got it
this is a code channel, that is not a code issue. Delete and ask in #🌐┃web
(after first contacting the publisher of the asset)
Hi.
I tried to play some videos with VideoPlayer on RawImage.
I wrote code to load a VideoClip from Adressable and assign it to VideoPlayer.Clip, but the error output just says "Cannot read file". What is the cause? Sorry for this amateur question.
The question isn't amateur, how you asked the question is though
You need to provide information on what you're doing for others to be able to help
I wanted to use this code to overwrite the VideoPlayer source, but the editor error output just said "Cannot read file", so I don't know what is wrong.I would like to know what is causing this error.
So you have done absolutely no debugging
How to get a bounding box that equals an orthographic camera space
or see if a bounding box is visible in screen space
you cannot get a bounding box for an orthographic camera as the z is, basically, infinite
I'm trying to get a 2D bounding box kinda
I'm programming a renderer for my world, so I want to be able to know if a chunk is in the screen before rendering
Use these two^
Thanks!
Help me!! I am spawning NPCs from a prefab, and I want them to follow a path of waypoints. If I put the script onto the prefab, then I can't assign it the waypoints which are GameObjects in my scene. If I put the script onto an empty GameObject in the scene (and call it NPCmanager) then I don't know how to dynamically assign it to the spawned NPCs. Any suggestions?
If you have a link to a tutorial or any advice, I'd love it!
the script needs to be on the NPC, assign the waypoints when you instantiate
typo\
Gotcha, so the behavior script (to follow waypoints) sits on the prefab. How do you assign the waypoints then?
how have you declared the waypoints in the script?
that is not what I asked
It would be good if I could see them in the scene, but no mesh renderer so they are invis in the game.
What did you ask? Sorry, I'm a bit of a noob.
Do you want me to paste the script?
!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.
It's small. I can post it here, am opening the project right now. ChatGPT helped me make the script, but not exactly how you described. It doesn't sit on the NPC.
To clarify, I'm using a 3rd party asset called Ultimate Spawner 2.0 by Trivial Interactive to spawn the NPCs. The spawner has some extra features, such as events you can use. I've tried using an event called On Spawned (transform) to run a method that's supposed to assign the waypoints to the spawned NPC. The method is on an empty object called WaypointAssigner in my scene, to which I can add the waypoints since it's in the scene with them. But this is not working for me.
Let me post the scripts here:
using UnityEngine.Events;
public class WaypointAssigner : MonoBehaviour
{
public Transform[] waypoints; // Array of waypoint transforms
public void AssignWaypointsToObject(Object spawnedObject)
{
GameObject myCube = spawnedObject as GameObject;
if (myCube != null)
{
AssignWaypointsToCube(myCube);
}
else
{
Debug.LogError("Assigned object is not a GameObject");
}
}
private void AssignWaypointsToCube(GameObject myCube)
{
AdventurerRoutine adventurerRoutine = myCube.GetComponent<AdventurerRoutine>();
if (adventurerRoutine != null)
{
adventurerRoutine.waypoints = waypoints;
}
}
}
I didn't format that right, sorry.
Currently I'm just using a cube to represent the NPCs, calling it myCube.
that looks fine, show the code for AdventurerRoutine
using UnityEngine;
public class AdventurerRoutine : MonoBehaviour
{
public Transform[] waypoints; // Array of waypoint transforms
public float speed = 1.0f; // Speed of movement
private int currentWaypointIndex = 0;
void Start()
{
// Check if there are any waypoints to go to
if (waypoints.Length > 0)
{
StartCoroutine(MoveToWaypoints());
}
}
System.Collections.IEnumerator MoveToWaypoints()
{
while (currentWaypointIndex < waypoints.Length)
{
Vector3 targetPosition = waypoints[currentWaypointIndex].position;
while (Vector3.Distance(transform.position, targetPosition) > 0.1f)
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
yield return null;
}
currentWaypointIndex++;
}
gameObject.SetActive(false); // Disable the GameObject when all waypoints are reached
}
}
This is a screnshot of my Infinite Spawn Controller, and you see the On Item Spawned (Transform) event.
I cannot assign a game object dynamically there, I don't know how.
Dont see anything horibly wrong with that as long as your spawnObject (myCube) has the AdventurerRoutine script attached to it
myCube has the Adventurer Routine script.
I think the problem is in the Infinite Spawn Controller, you see there is None (Game Object) there.
you have not assigned myCube here
But how? The cube is just a prefab until it spawns.
It doesn't exist in my scene.
Do I drag the prefab there from the Project window?
looks like you are using the asset incorrectly becaue there is no spawning going on there
I see. By the way, I don't have to use the spawner asset if it's simpler a different way.
And the cube does spawn in my scene, it just doesn't do anything.
this should be
GameObject myCube = Instantiate(spawnedObject) as GameObject;
then no asset required
then you can put the prefab in the event
replacing the one that looks very similar to it
read your own code
GameObject myCube = spawnedObject as GameObject;
I see it, it's in WaypointAssigner.
using UnityEngine;
using UnityEngine.Events;
public class WaypointAssigner : MonoBehaviour
{
public Transform[] waypoints; // Array of waypoint transforms
public void AssignWaypointsToObject(Object spawnedObject)
{
GameObject myCube = Instantiate(spawnedObject) as GameObject;
if (myCube != null)
{
AssignWaypointsToCube(myCube);
}
else
{
Debug.LogError("Assigned object is not a GameObject");
}
}
private void AssignWaypointsToCube(GameObject myCube)
{
AdventurerRoutine adventurerRoutine = myCube.GetComponent<AdventurerRoutine>();
if (adventurerRoutine != null)
{
adventurerRoutine.waypoints = waypoints;
}
}
}
Like this, right? And no other changes needed?
only assign the prefab in the inspector
and, of course, actually add some waypoints to the list
Well, no errors, but the cube still just sits there. I have the waypoints assigned to WaypointAssigner:
Ohhh
It moves! It moves!!!
OMG I almost had an anneurism.
Thank you so much, Steve!
May I bother you with another question?
Sure, bear in mind this whole thing is much more complicated by you using an asset to do basic stuff
In my game, the NPCs don't have physics. They don't have navigation etc. They just move from one point to another, in a linear fashion. (Or at least they should.) When the cube in this case follows the waypoints, it seems to interpolate or make a curve.
Is it possibe to tell it to go in a linear way, straight to the waypoint?
I can capture a video if that helps.
(Yes, I should do this basic stuff myself, but I thought the asset would make it simpler as I'm a noob. I should just learn to code better.)
this code
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
says move from A to B
so I dont see where a curve is coming from although you might want to look at Vector3.Lerp
Sorry about the messy scene, just showing you the cube going through the floor.
But don't worry about it, I will figure this one out on my own/
Thank you for your help, you have no idea how helpful that was for me.
There is a problem, I press the space bar and the panel is removed, I do not understand what it is... I didn't put anything anywhere. Can you help me please?
that looks fine. you should look at the scene view with your waypoints selected
Haha, the pivot of the cube is in the center of it, that's why it's going into the floor. Simple problem, sorry to have bothered you. Again, thanks for all the help!!
I will learn how to code better.
np, we all started somewhere, you are doing good so far
!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.
Why every guide want to find object by tag instead of by name?
it's faster
but, neither of those are recommended in general
By faster is the processing?
there is no other meaning of faster
Then what should I use T_T
ideally direct references in the inspector
otherwise some mix of opportunistic assignment and the singleton pattern or other dependency injection.
hey, I'm trying to change images of my imagecontainer (a panel that holds 5 images) by clicking on buttons. But the only way that it works is after I've clicked 5x on the next or the previous button, all images get loaded at once ._. can somebody help me '^'
https://gdl.space/vofepobaje.cpp
What is Direct references? like resources.load?
images[i].SetActive(i = imageNumber);```
you wrote = when you should have written ==
no
direct reference is assignment in the inspector
Resources.Load is the exact opposite of a direct reference
omfg
AND THAT TOOK ME 45 MINS TO FIND
@fickle stump Don't spam off-topic images
is direct reference making public attribute and drag and drop asset?
sorry didnt know that thats spaming 
yes
Ahhh...
@wintry quarry I've tried your fix, but somehow the the index only changes after beeing clicked 5 times..
it gets triggered at once after 5 clicks
if (imageNumber > images.Length)
{
imageNumber = 0;
SetImage();
}```
you're only calling SetImage in that if statement
why
shouldn't you be calling it no matter what?
some simple debugging will get you these answers in the future
all the more reason to learn how to debug properly
How do you change attribute inside prefab? Do you just make a new class with constructor to change certain attribute?
I want to generate text with certain font but different text everytime
in what context?
no, you cannot use a constructor on a script attached to a gameobject/prefab
Spawn the prefab, then change text
instantiate the prefab, then change the text on the instance you created.
(idk if this counts as really beginner coding so sorry if this is the wrong channel)
Does anyone know why my AddExplosionForce() is applying way too much vertical force and not enough horizontal force?
(also hi everyone)
Presumably the position you used for the explosion is wrong or you added too much "upwardsmodifier"
Sounds like you should start debugging
yeah
I keep forgetting not to say uh 😭
The point that the explosion is from should be right in front of the player
do you seriously expect an aswer when you supply absolutely no context?
For debugging positional things, stuff like Debug.DrawLine are helpful.
and the upwards modifier is very low
okay fair
print it to make sure
I can try to give context
lemme try this first
Although I do apply the explosion force through an external method
like the method is in a script on a different object
By the way, the explosion force sends the player extremely high up even if it's in the negatives (down to -1)
Let me jsut repeat this
Yeah
It worked, but I want to make the position relative to my canvas instead of my camera , how do i do that?
usually for UI you instantiate it as a child of some container UI element
and just set up anchors/etc in the prefab
Instantiate(prefab, container)
I successfully make it as a child of a canvas
but somehow the position still wrong .-.
again, proper anchoring etc
you are giving vague answers here so it's not clear what the "correct" position would be
I'm not sure if this would exactly be what you meant, but you could try anchoring the text to the corner of the canvas instead of the center
like this
for (int i = 0; i < HighScoreList.Count; i++)
{
var temp = Instantiate(Font, new Vector3(50, 160 - i * 100, 0), transform.rotation, GameObject.Find("CanvasHighScore").transform);
temp.GetComponent<TextMeshProUGUI>().text = "Score : "+HighScoreList[i].ToString();
temp.GetComponent<TextMeshProUGUI>().anchor
}```