#๐ปโcode-beginner
1 messages ยท Page 131 of 1
IDE not configured...
that does nothing to the thing you passed into dropHeldItem()
Ye that is not a variable
there is an awful lack of syntax highlighting for unity's methods and types. get your !IDE configured
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
(this step is required to get help here)
I configured it the way it said
this is just how it ended up
Hi!
you either missed a step or you need to regenerate project files
if it didn't work, ask for help instead of just ignoring the problem
the most important thing you need is intellisense
@sacred orbitYou're also approaching the problem incorrectly. What you are holding in your hand should be a variable in your character class, and set that to null
thank you, this worked
now go fix your code editor before you do anything else
Does this 'unity script' thing at the top mean my one is configured right?
yes
also MonoBehaviour is highlighted
!docs
that's good then, just making sure
and it turns out you fix this by making sure to serialise a class instead of the list itself. Works now even if it's a bit messy
in case anyone else had a similar issue
should i join a game jam?
guys i can teleport somwhere in a scene but i want teleport to another scene to a location that i assign how can i do that
yes
when can i start
@tribal zephyrYou dont need our permission
read the jam rules
when will it happen
When it happens
how to check
okay thanks
So I've got a dictionary that's supposed to link an inventory item slot from an inventory container full of items, to a game object that represents that slot as a UI element on the screen. When the scene loads it looks at the inventory, creates the UI elements and creates the entires for the dictionary so i can later change the details of the ui element when the item details change, and upon loading the dictionary seems to be getting the right value and properly generating the key value pair.
UpdateDisplay is then called when a new item is picked up, but now the values of the dictionary are just null. And I've still got no idea what is causing it. had to develop a messy workaround before but its come back to bite me in the bum
and so an exception is thrown saying it's been destroyed, but between loading the scene and updating it nothing actually changes with the gameobjects
is itemsDisplayed the dictionary you are serializing to json?
no that's something else sorry. I'm serialising this container of slots, the dictionary should just stay in the scene
instead of sharing these tiny snippets of code that aren't showing the full picture and are screenshots that discord is cropping making it incredibly frustrating to read, you should share the full !code correctly
๐ 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.
yeah that's a bit nicer https://hastebin.com/share/dehuguhixa.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
notice how you call DisplayeInventoryOnLoad then immediately after that you assign a new Dictionary to itemsDisplayed
you're doing it backwards
just spotted that after posting, will see if that resolves anything
and for future reference, always start with the first error in the console. it usually causes subsequent errors
well it should considering you would have received a NullReferenceException in DisplayInventoryOnLoad
in this case the two dictionaries after the load was an attempted solution on my part, seeing if I could make sure that the dictionaries are re written on load. I still had this issue a few days ago, but it was just the values that were null, not the dictionary as a whole
then where do you assign to the dictionary before Start is called?
does anybody know code for getting all the users in a list from firebase realtime database using REST API
need to get list of these
this is what I had before, just moved the new Dictionary ones down a bit https://hastebin.com/share/risujixebu.csharp With it this way round, it adds the gameobjects properly when the scene loads, but then when I go to update it's just null
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
as if the gameobject is deleted, but it never is
but it never is
then what isDestroy(uiObj);
since the inventory is supposed to update, then this runs, that was initially going to be what handled removing the UI element. but since the inventory is a list, that does nothing and is never run
by the way, you know you can throw a component on those objects that has something in OnDestroy to let you know if it is being destroyed
so just a script that posts a log?
sure
that might be useful
I know on scene changes it should be destroyed, is there a way to check to see if one was destroyed specifically because of switching scenes to see if they are being destroyed within the same scene?
is this the dan pos inventory tutorial?
probably
been using a fair few to get the ball rolling
don't recall the names of them
but I use them to give myself some direction on what to learn
did you have a problem where selecting things from the hotbar are inconsistent?
like sometimes it will pickup, other times not
haven't got a hotbar, only functionality I have is clicking an inventory item to remove it
ran it through and it only destroys the objects on scene change, as expected, no clue then why mid scene it just vanishes :/
although one ui slot seems to be destroyed twice on scene switch which I don't understand
wait is it normal for the values of the script on the prefab to change during gameplay?
that on the right reflects what I last picked up, but I didn't think it was supposed to
It shouldn't. Sounds like you're modifying a prefab, rather than an instance of a prefab
maybe that could be where the rest of the issue lies
public class DisplayInventory : MonoBehaviour
{
public Inventory inventory;
public Dictionary<InventoryItemSlot, GameObject> itemsDisplayed = new Dictionary<InventoryItemSlot, GameObject>();
public Dictionary<Structure, GameObject> structuresDisplayed = new Dictionary<Structure, GameObject>();
public RectTransform scrollParent;
public GameObject slotPrefab;
public List<InventoryItemSlot> inventorySlots;
private void Start()
{
//Use a c# callback deligate to call the UpdateDisplay method on item pickup rather than continuous updates
inventory.onItemInventoryAdded += UpdateDisplay;
DisplayInventoryOnLoad();
}
private void Update()
{
}
public void DisplayInventoryOnLoad()
{
/* Iterate through the player's inventory
* Simply create an inventory element and set the count and colour to the right value
*/
if (inventory.invContainer.Count != 0)
{
for (int i = 0; i < inventory.invContainer.Count; i++)
{
slotPrefab.GetComponent<InventoryUiSlot>().CorrespondingInventoryItem = inventory.invContainer[i];
slotPrefab.GetComponent<InventoryUiSlot>().inventory = inventory;
var obj = Instantiate(slotPrefab, Vector3.zero, Quaternion.identity, transform);
obj.transform.SetParent(scrollParent);
itemsDisplayed.Add(inventory.invContainer[i], obj);
itemsDisplayed[inventory.invContainer[i]].GetComponentInChildren<TextMeshProUGUI>().text = inventory.invContainer[i].count.ToString();
itemsDisplayed[inventory.invContainer[i]].GetComponent<Image>().color = inventory.invContainer[i].item.color;
}
}``` Since I pass in the prefab at the top to create the object, I assume me changing the slot prefab is doing that then
you shuldn't be modifying the prefab, yes
you should be instantiating the prefab to get a new object
then modifying that object
And you are doing that
just partially
you're just doing it after messing with the prefab
also, instead of slotPrefab being a GameObject, it should really be an InventoryItemSlot
or..an InventoryUiSlot? I can't quite tell
question, why are almost all examples of MonoBehaviour classes without any input parameters - and instead they declare public variables below and empty parameter class declaration?
what do you mean "input parameters"?
sorry bout the names being confusing, it's a cobbled mess at the moment
are you talking about constructors?
You can't construct a MonoBehaviour yourself
ah, I see
but since I need to change the text of the UI element that exists in the scene, I assumed i needed to hold the actual game object right?
Unity constructs the object and then applies serialized properties afterwards
So you can certainly write a parameterless constructor and do stuff in it
ok perfect. good to know
this discord is great
but:
- you can't meaningfully use it yourself
- serialized properties won't be applied yet
no prob!
MonoBehaviours can't exist on their own; they have to be on a GameObject
hence the constraint
I do often wind up writing an "init" method that feels a lot like a constructor
because Awake runs too soon (as part of Instantiate/AddComponent) and Start runs too late (on the next frame)
oh hang on, I may have an idea
ok slightly unrelated question. I'm trying to understand the pros and cons of these two implementations of 2D ground detection:
if (collision.contacts[0].normal.y > 0.5f)
vs
if(collision.GetContact(0).normal == Vector2.up)
The latter only works if the normal is exactly the up vector
i feel like #1 is superior because it can work on ramps
well, within a very small margin, since Unity does that for you
nah, it's probably even faster than the second one
ok nice
given that it only cares about 1 number
it's basically meaningless though
I would look at using Vector3.Angle(normal, Vector3.up) to get a more meaningful value, though
It's less intuitive for me to say what this means:
if (normal.y > 0.5f)
than what this means
if (Vector3.Angle(normal, Vector3.up) < 45)
do yall tend to use rigidBody.AddForce for jumps as opposed to rigidBodyb.velocity = new Vector2(rb.velocity.x, jumpForce);? I tried the addForce and the jumps were... "weird"?
hard to describe
idk why, but my double jumps are sometimes "weak" with addforce
I used Impulse
if you call AddForce every physics update, that makes you push on an object that hard
okay, that's more reasonable for a jump
But yeah, you'll still get different behavior
You're changing the object's momentum by a fixed amount
yep
rather than just directly changing its Y velocity
huh, now displayInventory itself has been destroyed? but that's just the script on the Ui container. This is making me go 
you are very helpful
For a more "realistic" double jump (maybe a rocket pack), AddForce makes sense
but if you want an arcadey one, go with velocity changes
yeah it seems to be a little more fluid
i'm at a complete loss :(
so evidently the gameobject is treated as being deleted, but it never actually deletes :/
is it possible to have the main camera follow a 2-D character with a "leash"? Like, there is an invisible box around the character and the camera moves with the player only when they are pushing against the edges of that box.
even after logging it I can't see it being deleted anywhere
not sure if i need a script for that, or if I do this through the unity UI
use cinemachine
ah, any hint on where that is?
It is a package.
it's a package. there's documentation on how to use it pinned in #๐ฅโcinemachine
ah, that's for 2D also?
yes
ok cool ty
made it so it says when the two slots where created, but even though it says right there that they've been created, still doesn't like ut
well, you'd better look at exactly which line is throwing that error
line 79, the line below this one, all because this returns null
that's all its giving me :(
Hello, trying to instantiate model and so on on UI layer.
op.layer = 5;```
This actually does the work... for the parent. But the children all still have "Default" layer.
do I make some sort of ```foreach GameObject in Parent
GameObject.layer = 5;?```
to get all the children to UI layer?
also if this is a try get value, how come it's returning with null? Surely if it's null it would move on to the else portion?
i actually have an extension method that changes the layer of all of an object's children all the way down to the lowest level. gimme a sec to find it for you
public static void SetLayerRecursively(this GameObject obj, int layer)
{
obj.layer = layer;
foreach (Transform child in obj.transform)
{
child.gameObject.SetLayerRecursively(layer);
}
}
just drop this into a static class like GameObjectExtensions. then you can call it on any gameobject
ahaha ๐ I am so noob that I have no idea where to find that static class
create it
oh
I think I might just have to try a different system other than a dictionary
would it be worth simply having a list of itemSlot objects and a list of gameobjects instead?
does it also change the parent layer?
it changes the layer for the object you call it on and all of its children, grand children, etc. all the way down
kaay, seems like I did set this up, let me try ๐
works like a dream, thank you very much!
Hey guys sorry i cant find anything like this but. Is there any website or app that makes you solve C# problems like some kind of duolingo but C# version? lol
A popular one is LeetCode, and others like that. (Just google "sites like Leetcode")
There is SoloLearn which I guess is more analogous to Duolingo
Or just guides like w3schools, or microsofts tutorial
Resources pinned in #๐ปโcode-beginner too
thanks
Hey does anyone know how to repeat an if statement if somethinng is or isnt true? For example shoot a raycast but if raycasthit is null then repeat the raycast
Make a loop
Just a loop that breaks when successful I guess
Like a coroutine with a while
can you use a 2D box collider in unity 3D?
also is it possible to shoot a raycast and have it pass through all colliders that don't have a specific tag?
for example pass through everything with the "Wall" tag and only stop if the raycast hits a collider of an object with the "Player" tag
Yes the raycast has a layermask parameter
thanks
how do I find the only child of gameobject without knowing it's name? ๐
GetChild(0)
Wait, gotta look up the correct syntax
Edit: fixed
thank you very much
Ok cool.
That was right
https://docs.unity3d.com/ScriptReference/Transform.GetChild.html
and you can use GetChild(i) in a for loop to iterate through children
@visual hedge Oh, no it wasn't. Parens, not square brackets. Like caprisun said
for example this is from a for loop that does an operation on every child except the "Frame" child
perfect, thank you
Since they said there is only one child, they can just pass 0 instead of looping
oh yeah true\
so if I do a raycast like this, does it ignore everything except for objects with roomMask or does it ignore everything with roomMask
The former. Only hits things flagged in roomMask
alright and how do I add roomMask to something
roomMask is like a list of layers (it is a series of 32 bits that act as true false flags for the 32 available layers).
I would just make a Layermask variable
[SerializeField] Layermask roomLayer;
and set it from the inspector.
Whatever layer you want to capture can be selected. More than one too
Or you can invert it to only NOT hit the given layers with ~roomMask
wow that was easier than I thought
I had it already added a serializefield I just hadn't checked to see it was a simple dropdown
Definitely. They are intimidating at first, but very simple and powerful
honestly not even intimidating
how do I outline a blank GameObject's hitbox for debug purposes
I have a blank GameObject on each corner and each one should have a 2D BoxCollider but I want to visually confirm size and location
collider does not create collision shapes?
following a tutorial and am getting this error while they arent, even copy-pasted their provided github code and still doesnt work, any suggestions?
yup yup
is there a pause keybind?
P i think
I have a GameObject that only exists when I hover over something
thanks
its something like that
you're using it like a boolean..
unless IsPointerOverUIObject() is of type bool it wont work..
a void IsPointerOver() will not work.. b/c it doesn't return a bool
public bool isPointerOver(){
//code
bool newBool = true;
return newBool;
}
something like this would work.. b/c when you call isPointerOver() its returning true in that little sample code..
so it would work in your code b/c it basically would read..
if(true)
{
..blabla
}```
the github i found shows it as a bool
you got to set up the entire system, b4 it would work like its printed on the github..
in his InputManager script it's all setup like it should be
if ur not finished with InputManager or have changes it could error like you see now
yup it was wrong in input manager, thanks
Hey guys I've made a settings scene with UI, etc. Now I'm not sure how to make the variables save to work in other scenes. Is this a feasible approach? like do people usually make a scene just for settings
you can sure.. or just a gameobject u enable and disbale
look into JSON or PlayerPrefs..
PlayerPrefs is easier.. not as robust.. and used for things like settings
why does my game stop once it executes
Once it executes what?
once i press play
no
Ok, well its just guesses until you provide your code. Whatever changes you made before it started happening.
Is there a "while" ANYWHERE in your code?
if you have an error and have Error Pause on it will hapen
thank you ๐
show the console if paused
Thanks a lot!
thats the default, correct?
iirc yes
That should have been super obvious, so i discounted that as the reason haha ๐
depends.. i asked if its default b/c i had a problem like that when making my loading system.. when my game loaded in it would just Stop... i had some NRE's in the console.. but thats common sometimes for me as i work thru things..
and thats what it was.. i sat there looking at the NRE for 30 min or more.. and still didn't connect the dots
lol ๐
Fair lol
an NRE? pft, I got bigger fish than that to fry
i gotta fix this other error..
NRE laughs in "Other Error"
im making an fast pace fps game like ultrakill and i dont know whats better for maintaining movement speed mid air character controller or rigid body
this also screwed me.. there used to not be that dialog message there in the console when u had a search term in there...
i accidently put something in there once while trying to look thru my project folder.. didn't realize it was there.. and my errors completely wouldnt show up
thats just a small bit of the puzzle.. the answer tho would be Rigidbody..
how do you log what a layermask's name is
thats how i thought
the whole thing screams Rigidbody tbh
im stuck on this shit for past 2 weeks
thanks
just a spam deterent... for like when people use ^ to point to a message above you
add a few periods at teh end.. ๐ lol
yeah
They all have ups and downs. Unity's own controller does come with ground detection and stepping up stuff. That stuff is horrible to code yourself.
It's true that it does feel quite a lot like a rigidbody-type movement. Be aware that you can achieve the same movement in both paths though.
I can say thanks but not thanks*
you keep console window in a separate tab? ๐ฎ
i keep it docked down here
but sometimes i keep it expanded on 2nd monitor..
i still don't know the most performant layout LoL
game view getting no love :(
just kinda wing it
is there anything special i need to do for mobile..
if i want my game to be landscaped?
i just design it in that orientation i assume.. not so sure tho.. tbh
also i guess i oughta just look up some starter stuff.. no clue even how to get Unity Remote to work..
if I just remove the layermask, this works fine but for some reason if I add the layermask in the raycast none of the if statements conditions are fulfuller
and sending an APK over my phone to test all the time sounds horrible
did you click the layers you want inside the Layermask variable of the inspector?
yeah they are all the right ones
and the things ur targetting are set to that layer?
if you use a layermask in ur raycast it'll only detect things on those layers..
for some reason the debug.log is outputting Default
which isn't even an option in the switch statmente
wow
that would be layerMask
its still the PMs and I just did that
if you want to test a build you can always use an android emulator on your pc, then you wouldn't have to constantly be sending the build to your phone
thanks for the advice, i'll look into that
finally got my first phone with a Gyroscope sensor..
figures its about time to do some Mobile Developing
wait wym I'm debugging LayerMask
I thought LayerMask.LayerToName() outputs the layers name
you see here?
you would debug mask.LayerToName()
b/c ur LayerMask is called mask
it isn't called LayerMask
LayerMask is the type..
wait is that my code
wait I'm confused what is the syntax to debug.log a layer's name
think about it ^
like here.. if u want to move the myTransform's position
you type myTransform.position =
you dont type Transform.position =
your setting the position of a Transform thats called myTransform
you don't set the position of the type that is Transform
public LayerMask myLayerMask;
if your doing anything to this variable it would be myLayerMask.whatever b/c ur modifying the Instance of a LayerMask..
ur not trying to modify the main definition of what a LayerMask is
oh I thought LayerMask.LayerToName() was a function of the LayerMask class
that outputs the name of the layer as a string
yea, LayerMask is what type goes there..
it could be anything.. thisLayer.LayerToName(); or myLayer.LayerToName(); or.. aReallyLongStupidNameForASimpleLayerMask.LayerToName()
etc
well the index of the layer as an int
oh yeah layer 0 = default
like if you want it to print out all the names of all the layers in that mask
idk how to do that
I just want to know which layer that variable is set to
ensuring I am filtering the correct layer
can't u just peak at it in the inspector?
it shouldn't be any different than what u have selected in the Inspector..
unless you manually set the layermask in ur code somewhere
oh yeah I can serializeField it
something is setting the LayerMask to Nothing every single frame
what really confuses me is my serialized fields arent showing up
in the inspector
ya, that shouldn't happen.. when u set the layermask and press Play it should remain how u set it
unless ur code is changing it somehow
https://hastebin.com/share/kiyizuzuji.csharp https://hastebin.com/share/usavasejef.csharp these are my two scrips, NullReference on the Start of the Second Script pops up
a static variable doesn't work like that
my code is changing it via switch statement but the only outputs are wallMask and roomMask nad Default
not nothing
pretty sure u can't Serialize it
oh yeah I made it static
setting LayerMasks are some kinda voodoo that I never learned
i normally just set up a couple of masks depending on what i need and just use those different masks in code..
rather than trying to change the layermask at runtime. by using bit shifting
or w/e that magic is
masks are bitmasks. Binary operations lite bit shifting work on 'em
missing out on bitwise enums so you should learn
pretty sure ur error is in Awake
and not in start.. since ur start block doesn't have any code in it
I had this error begore Awake
i think its how u try to make it into a singleton
how? Awake happens before Start
ahh its ur 2nd script
its probably trying to access the GameManager Singleton b4 it gets set up
change the order of execution so that the singleton is first.
^ this is a good idea
But Singleton is made in the Awake already, which is before Start
yea, but its a Start from another script.. not the same script..
if u were accessing it in Start of it's self.. then there would probably be no issue
all Awake run before any Start in the scene. If you're sure you're only interacting with the singleton in Start, then you should be fine.
if (instance != null)
{
GameManager.instance = this;
}
else
{
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}```
are u sure this is correct??
if instance is not null.. then set it? if instance is null, then destroy yourself?
so... if instance doesn't exist?
destroy the thing that sets it up?
Oh my gof
brotha'
๐ lol
im soo used to Singleton errors being execution timing stuff like LEO mentioned
you threw me a curve ball with the bassackward if statement
thanks a lot
np
yup, Layermask.NameToLayer() eludes me..
no clue how it works..
public LayerMask clickable;
private void Start()
{
Debug.Log($"The layermask you defined is: {LayerMask.LayerToName(clickable.value)}");
}```
like I can set this up... and,
- If I have (one) layer selected.. it debugs the name of the layer directly below it..
- If I have (more than one) layer selected.. it debugs nothing..
sooo... not sure how you'd get that to list out the Name's of the layers selected on that LayerMask
could make your own method for that
yup im going to need to now..
๐ tinkerer's mind n all
not too sure why single layer print values would be off though
not sure to be honest
i could probably just (value -1)
to get a single layer.. but now i just wanna show all of em.. but thats perhaps a different day side-project
Layer indices are not the same as layer masks
ahh, that makes sense
LayerToName operates on a layer index which is a number 0-31
Layermasks are bitmasks
They aren't interchangeable
well TIL (a little bit more) lol
i always learn a bit when talkin about layers and layermasks
haha, a bit more.. snare drum
Would some kind soul be able to tell me why scipt b doesnt see a return value from scipt a?
Also whats best practice for sharing code here? ๐
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
tyty!
found what looks like a good little explaination
shall read and learn something hopefully
wait.. is binary 1:1 for addition and subtraction? so the binary of 1 + 2 = the binary of 3?
๐ holy crap, did not know that tbh
wait, this may or may not be true, let me do a quick test lol.. bitwise operators and bits in general make my head hurt
script a) https://hatebin.com/nglpqfiqtw
script b) https://hatebin.com/qmfohwgtvm
once u post it up im sure someone can help ya out.. common thing people say around here is don't ask to ask..
just ask
ahh there they are ๐
how do you check for a collider on the same object that the script is running from, I have 2 colliders on a object, one for collisions and trying to get one for jumping. I am unable to figure out how to find it
float[,] heightMap = this.noiseMapGeneration.GenerateNoiseMap(tileDepth, tileWidth, this.mapScale); so this doesn't return anything?
Binary is a different way of writing numbers. It doesn't change anything about arithmetic. 1+1 is still 2, 2+2 is still 4 and so on
Now there are other types of arithmetic you can do with it like bitwise operations
But every number in your computer is ultimately written in memory as binary
and its safe to assume it doesn't convert them back and forth to do calculations
It doesn't
No sorry, let me rephrase. In script b's BuildTexture function it doesn't see noiseMap as a variable which should come from script a.
starting to get it
It only gets converted to decimal generally if you do like ToString()
I am bad at questions sorry
you can use a GetComponent<TypeOfCollider>
that will try to find that type on the same object as the monobehaviour
or if its a child object or something theres functions for that too.. such as GetComponentInChildren
im trying to capitalize after a space in this function. Am I close or is there an easier way to do it?
(I dont want to use the Name option in textmeshpro)
string newString = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(myString.ToLower());
try this on for size
may fit ur needs, may not tho if you only want it after spaces
do you know what myStats.inputField.text[-1] returns?
use TextInfo.ToTitleCase instead
oh you got it already
this works, is this how I should use it?
var txtinfo = CultureInfo.CurrentCulture.TextInfo;
Debug.Log(txtinfo.ToTitleCase(myText));
have you done any Debugging? i think that questions over my pay-scale..
can you debug the values at the end of the function to see what its coming up with? maybe work backwards from that..
like you could Debug the noise float after u set it..
also debug the noiseMap value before u return it. just to maek sure everythings working like u expect it to?
or ask again later i guess when theres more activity of some better coders lol
yeah, correct
i mean newString is relative.. u can call it anything u like.. but yea.. looks fine.
Trying but this tutorial might just be not so good tbh.
I can kinda descibe the problem better, it seems the variable noiseMap is not global/public i just dont know why. Still appreciate the help!
no, -1, is the index you're attempting to grab. that would cause an error . . .
yeah I get its a syntax error, I just meant it as pseudocode tbh (using python brain)
care to share the tutorial you're following? it may not be the best way.. sometimes they're not. but if its a relatively older tutorial and hasn't been taking down.. then it most likely will work
btw you don't need .ToLower there the ToTitleCase will reformat it anyway
Claims to be from 2022 but guess it depends on how you define outdated haha.
https://gamedevacademy.org/complete-guide-to-procedural-level-generation-in-unity-part-1/#Unity_Procedural_Generation_Files_Requirements
ohh those are always fun..
Sebastian Lague did one on youtube.. its a Long series.. but even his has little errors here and there.. and u have to skip back and forth from video to video. to gain enough context to get it working correctly
tough system to get working flawlessly
oh yea, he charging for courses.. im sure thats a decent tutorial.
Yeah its why im inclined not to give up cause its been a bit now and for something that seems so simple it feels user error to me
Was gonna look at another but if I do it will be tomorrow I dont have the energy tn lol
if u get stuck, dont throw it away. just save it where u are.. move on to something different.. give ur brain a relax and come back to it..
sometimes it just takes a breather to see a mistake you've overlooked countless of times
i got some work to do.. but imma bookmark this page and skim it when i get some time.. i'll give you a ping or something if i find anything wrong... but im betting its just something small thats been overlooked
Oh for sure wont throw it, and I much appreciate that thank you!! Absolutely no rush to get back to me on this!
hey there. Im making a 2d top down space game. And I want some astroids going about in the background. What is the most effective way of moving meshes from a to b. Performance wise.
How many?
Well, that depends. But Im aiming for about 250
Moving them with translation isn't going to let them be physics reliable, and that many rigidbodies should be okay but you'll likely have a lot of other things too.
Could consider DOTs though for the asteroids
Then you can have as many as you want without much worry
Without physics it would be a lot better wouldnt it?
What is dots?
I'd imagine you'd want some physics on asteroids, if you intend on hitting them?
Simply put, it lets you have a lot of stuff
No I have that in the foregorund. I want them to be in the background for aesthetics
This will prop be it
Then particles could also work
Is that more efficient than dots?
Impossible to say
But VFX graph allows for millions of particles, more than enough for what you'd need
I see. Thanks for the info. Ill have a deeper look into dots for now. It looks quite promising
without physics: vfx graph
with physics: probably dots
probably just wanna use vfx graph it sounds like
Yeah, but dots seems not very heavy. So the little astroids in the back actually colliding would be very cool. Osteel just opened a new door for me
Can dots be multithreaded easily? Or does that take a hole new mountain of custom work?
you can do gravity force + collission operators in vfxgraph for your physics simulation
and they made gpu-instancing works in 2022 lts
Sorry, what does that mean?
Dots is a term for multiple packages. It is the Data Oriented Tech Stack. It includes Jobs which are easily multithreaded. It also includes ECS, which allows highly performant code with lots of entities, but is not required to use jobs (but is probably applicable here, unless you want those entities to collide with gameobjects too, in which case it may be too much work to be worth it)
Also includes the burst compiler and some other packages to support those three
Is there particle to particle collision support? I thought it's only specific to their AA box and collisional plane
How do I make a object point where the controller joystick is pointing at
dont crosspost
wow now 2 people have said that
i mean, yeah
its a general rule here and its in #854851968446365696 so youre gonna get multiple people telling you the same thing
if you had seen both posts that you should know someone else already said it
to answer your question
grab the vector for the joystick direction
grab the position of the object youre making look at joystick
oh right 2d or 3d
because you essentially add the vectors to create a point that it should be looking at
then either use transform.LookAt or calculate the angle
not if they saw the other post first, then came to this channel and saw it again . . .
long segments of code go into paste sites, not direct into discord
https://hatebin.com/hqvpdpejcb
ok soryy
welcome, when posting !code use a bin site for large code blocks or format the code if it's small (only a few lines) . . .
๐ 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.
meh i put a hatebin link in
needs to be a bot or something that does that automatically
aanyway
Hello!
This is my first code and I need help with two things...
- I know the code is bad and could be simplified, so could someone help me do that?
- How can I make sure that the images and numbers are remembered when changing scenes?
what images and numbers are you trying to remember
maybe im gonna show it
because you can either dontdestroyonload the gameobject which would make it exist in all scenes, write a save system or use playerprefs
When i change scen i want after back see Monster name : Nekker and number 18
When i back to this scene i just see number 0 and white screen
can u help me with that?
this is a summary, but should give you an idea. you need to create a save system to store the current card and its stats. you will save the currently focused card when that scene exits (and a new one is loaded). when that scene is loaded, you will load the save file and assign the stored card to the active (focused) card . . .
I guess it might be related to what you're talking about, but I'm on Code Beginner for a reasonโthis is my first project, and I'm completely lost in this. What you're saying sounds like black magic to me. So, would you be able to help me with this? It's literally the last piece I need to start working on expanding further parts.
can't help too much right now. you're best is to follow a tutorial on a save system in unity . . .
give the cards each a value, 0,1,2,3 that way its simple.. use playerprefs (look up tutorial on youtube), where they save a health value or something you would save the value of the card you want to save.. (the one you want to load back into).. then you do that, in a start method of a script or something load in the card (whichever one is represented by that value..
do u have time to help me with that?
!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
So about a week ago I was told to go through all of the c# stuff here: https://www.w3schools.com/cs/cs_getstarted.php and I believe I understand most of it, but now im starting to see that I dont understand how C# interacts with unity, does anyone have a similar 'tutorial' type site for those interactions?
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
thank you so much
Keep in mind that Unity is just an API built for C#. So it just gives you methods to call, and classes to inherit from, callbacks to listen to, libraries/packages to use, and whatnot
that's fair, I jsut basically went back to my project armed with new knowladge and i cannot figure out how to referance game objects and their components within the script, so i felt there was more learning to be done
Always more haha. But yeah, Unity does things a little different than a pure c# environment like a console app
This site helps with learning about references btw
ooo awesome, ill give both of em a go
i dont understand but unity picks up button presses from my touchscreen but not my mouse . literally just a normal button and i have an eventsystem, the issue persists on build
even ones that used to work // works now nvm just had to restart ?? lol
Ok i add option PlayerPrefs and now looks good but after change scene its still dont remember them!
Can somone explain me why?
Hey! I'm a bit new to coroutines, and I'm trying to play a recording of joystick positions at certain times, but it does not correctly line up with the Updates of the game. Maybe it is because of the yield waitforseconds? How can I fix this?
yield return null
it will wait for one frame
btw there is no way to duplicate the delta time between each frame (you can approach it though)
I spawn a prefab for an equipment system in UI that has a progress bar, once the equipment is "activated"(its a button) the equipment has different values one being a float for time. The progress bar will fill up in that secific amount of time in seconds.
Im using coroutines for the progress bar, since i instatiate sometimes multiple equipment at once, its a dictionary of coroutines so they each have their own progress bars running independant.
My question is, how would i go about saving the state of the progress bar? If the player leaves the game when a progress bar is 50% filled, when the game loads i want the coroutine to continue firing at 50% and go on.
Ive been stumped on this for a day now.
im playing an audio clip through an audio source but the audio quality sounds horrible its loud and it sounds like its playing multiple times at the same time
what do you mean if the player leaves a game? Does that mean different sessions on a built version?
i have a save and load system, when the Application is closed it will save the game. Im currently just saving and loading basic variables.
Im making a mobile game, its all UI
Alright, so the idea is you need to make another coroutine, but this new coroutine should have the last updated variables before you serialize the data for that session.
and by new coroutine I mean use what you have there but with the variables from where you left off (elapseTime should be sent in)
i will give it a shot! Thank you
you need to save the info.equipmentProgressBar.fillAmount and load it back. then elapsedTime will be fillTime * info.equipmentProgressBar.fillAmount. also, in UpdateProgressBarOverTime, there is no need for the parameter fillTime; in the UseEquipment method, collectionTime is a local variable stored using the EquipmentData instance. that instance, data, is passed as an argument to UpdateProgressBarOverTime . . .
how does 0, hit.transform.rotation.y,0 not meet the required parameter of float, float, float
eye your brackets parentheses a bit more
classic move
Is there any serious problem if I use Sublime text insted of vs code
don't forget that transform.rotation is not in degrees, if you want the Y rotation as degrees use transform.eulerAngles.y instead
just found that as everything is rotated 1ish degrees
if you do not have a configured IDE you cannot get help here
I don't need help "there"
well if you plan to never get help with any errors here, then feel free to use any IDE you want, including unconfigured ones
a smart move would be to use a supported IDE that is configured to use with unity so that you get proper syntax highlighting, autocomplete, errors underlined, etc.
Nice catch! You are right! Thank you for the help Iโll try this out
dude how am i supposed to reactivate my license?
it asks for a serial number
idfk
wow nvm it MAGICALLY started working
wow
usually license issues just require a restart or to return it and get a new one which only takes a few clicks. but also it's not a code issue so #๐ปโunity-talk for that in the future
whenever I import a model it comes with rotation how do I pre-emptively remove this rotation?
so whenever I instantiate a new one from /imported assets/ it comes not rotated
its greyed out
blender
there may be some options in the import settings, but otherwise you can always parent it
how do I change rotation to 0 through blender?
I tried rotating it in blender and reimporting it but then it was just rotated 90 degrees and still said it was rotated -89.98
blender has a different system of axis so it's something to look up when you export your model over
whats wrong with my code? its supposed to make the player in my game move around, but its not working. its also supposed to rotate the camera attached to the player but it can only rotate up and down
it says no errors
come on
anybody???
have you tried log the value from input manager first?
wdym
Hey guys. Not sure if i can ask this here.
I need some help. Im using unity and c#. In my project i have daily missions that are supposed to reset at midnight everyday.
I made a timer that counts down 24 hours and it will then reset my missions. But my issue is if a player logs in for the first time at say 1pm then their 24 hours timer stars from 1pm. Which means their missions will reset everyday at 1pm which i dont want.
Im not very clued up with the date time stuff. I tried googling but cant find a straight answer.
So if anyone knows of a tutorial or document i can read to try help me figure this out.
Of if anyone know what i should write in my code to make these missions reset at midnight for all players then i would greatly appreciate it.
Thanks all.
would be this based on local time or a server time
if local then you can probably just grab system time
Debug.Log(value you want to see);
you can just check if system time is at 00:00
and then reset if so
where do i put that
Is this ChatGPT
Why do your Update and Start functions have summaries
(jk)
i made them
I dont even comment my code that well
i said jk
Sure
nvm
put log in the place that you just fetch the values
int x=X();
Debug.log(x);
Like i said im not too good with this time stuff haha.
Im using system time.
How would i code that line to see if system time is at 00:00?
Also will the player have to be on at that time for it to reset? Or will it auto reset at that time even if the player is offline.
you know how to use it, you have already used it in your start
serialize the previous time they quit the game then compare it to when they start a new session
So like a playerpref save of last login time minus current time?
im more of a json person but sure
playerprefs isnt the best option for saving data...
its like not secure at all
Yeah i know. Im just using it for testing right now.
Everything will be saved to a binary or json later on
Im just not sure how to code the whole time thing to make it reset at midnight.
nothing is being logged
does OnTrigger methods only work when the other collider has either a Rigidbody or a Character Controller?
only when the collider is set to trigger
at least one GameObject involved in the collision must have a Rigidbody or CharacterController, not necessarily the "other" object . . .
ohh i see, because i was confused because my gameobject that had the trigger collider with the script and everything doesnt detect other colliders entering it, unless if it has rb or cc attached to it
you mean
int x=X();
Debug.Log(x);<---this line is not executed?
```the only possibility i know is there is exception being thrown is X()
i managed to make my player move but the camera issue is still there. any help?
Which part of the code you showed is rotating thr camera?
nvm i fixed it
it was in a different script i forgot to send a screenshot of that one
but now its fixed
thx for everyone trying to help out
i really appreciate it
can scriptable objects have functions that are used at runtime?
sure
Yeah
i fixed, just forgot to save script ๐ญ
Is there a way to calculate time taken ingame accounting for code complexity slowing it down? I know people say Time.deltaTime does account for it but not to my needs at least. For instance as a crude example, my crowd simulation slows down a lot when I do a Debug.Log every update (obviously). The FPS doesnt drop just the movement of the agents for some reason (still smooth just slower). This increases the elapsed time equally which I dont want. I dont want to include any overhead.
i remember someone has told you stopwatch class, or i recall it incorrectly
Im trying to create states for my animation. I want my player to be idle and be able to attack(maybe a rock or somthing) but also beable to move and attack. I have a few issues. First one is when i attack it stays attacking. how do i know when animation has finished. second is when i move and attack i swap back to idle then attack. this does not work. maybe im doing this all wrong looking for some guidence please https://gdl.space/azagiholuk.cs
probably your attack animation is set to loop, you have to disable that, I guess
if u are using any buttons like wasd to move u can add bool button true
Hey all, I'm calling this method and it doesn't seem to break properly (I think the while loop isn't breaking even when it should based on my coding understanding). The method is this:
public void ForwardLight()
{
while (Input.GetKeyDown(KeyCode.W))
{
forwardLight.gameObject.SetActive(true);
if (Input.GetKeyUp(KeyCode.W))
{
break;
}
}
}
and the part where it's being called
void Update()
{
moveX = Input.GetAxis("Horizontal");
moveZ = Input.GetAxis("Vertical");
if (gameOver == false)
{
transform.Translate(Vector3.forward * Time.deltaTime * speed * moveZ);
transform.Translate(Vector3.right * Time.deltaTime * speed * moveX);
ForwardLight();
}
just really unsure as to why it wouldn't break when the key is released?
It's not breaking because you wrote an infinite loop
The game engine is waiting patiently for your code to finish running before continuing with the rest of the game. But your code will never finish running because it's waiting for some future frame in which the key is released.
That future frame will never come because your code isn't letting the current frame end.
huh, I thought the break statement would execute once the key was lifted
I'll wrap it in a coroutine see if that fixes it
The key will never be lifted according to your code. Input data won't update until the frame changes, and you're not letting the frame end.
I don't understand why you think you need a Coroutine here either
All you need is two if statements, one for KeyDown, one for KeyUp
guys can I have a question?
You just did!
2 years ago lil bro ๐
If you turn on "Apply Transform" when exporting the FBX, the model should come in with no rotation
yes.
That consumed your question for the day
This causes problems if the model has objects parented to each other, though (like if you have an armature)
I use Apply Transform for basic props
I dont but I've been importing via just draggin blend files in and havent had an apply transform option
Also, I like to switch this to "FBX All". This gets rid of the 100x scale
how do i make a coroutine during which something happens, and not one that waits for some time
When you import a .blend file into a Unity project, Unity asks Blender to export to an FBX file with default settings
So if you want to make any changes to how the export happens, you need to export it yourself
is there a trick to serialize a List<MyInterface>, where all members are serializable? Can I just go for it or no?
Ah well was imported quite awhile ago
I would suggest using this handy add-on
It lets you export an FBX with saved settings to a pre-set path with one click
And all code is set up for rotated thing but I'll make sure to use that later
I keep all of my .blend files in a Sources folder that's outside of Assets
and I use that addon to export into the Assets folder
how do i make a coroutine that affects the gameobject of an amount of time and then stop?
instead of waiting some time, it does something for that amount of time
r u there?
not out of the box, I don't think..
yield return null when make your coroutine waits until next frame
is there an addon or some trick to it?
those exist? because that would be lovely
@swift crag
one minute. digging around in code
you know how the first time you browse through packages, you have no clue what most of anything is for? good to come back to it and find some gems
oh tnrd. i used his tags and layers package too
first, think about how to make a coroutine that runs forever
wait so you have or have not tried it?
I have used the interfaces package. I was talking about the layers/tags one
oh yeah. itโs really good. i can show you a pic of what it looks like
IEnumerator GoForever() {
while (true) {
transform.position += Vector3.up * Time.deltaTime;
yield return null;
}
}
This will move the object up at 1 meter per second forever
When you write code, you should always be thinking about the conditions that your code cares about
in this case, there is only one "condition"
while (true)
it's not much of a condition because it's always true
If you replace that with another condition, you'll get different behavior
okk
so i should use a separate coroutine which waits for that amount of time?
while (Random.value < 0.5f)
this would run a random number of times
it literally just autogenerates a class with public consts for layers/tags/layer masks
while (Time.time < 10f)
this would run until the current time is at least 10
that's not quite what you want, but it's pretty close
You could, but it would be unnecessary.
Time.time gets current ingame time
It's how long the game has been running for, basically
not real world time
accounting for time scale, and ignoring big lag spikes
so yeah, it's in-game time
now, consider this
if you set Time.timescale, then Time.time will move proportionally
IEnumerator RunForTime(float duration) {
float endTime = Time.time + duration;
while (Time.time < endTime) {
// ...
}
}
what does this do?
so if you set Time.timescale = 0, Time.time will not advance. Time.timescale = 2f makes Time.time advance at double speed
it's the time the game has been running + the time you want it to run?
That's what endTime is, yes.
So what does it mean when you compare Time.time to endTime?
so while the time the game has been running is less than how much you want it to run, it will execute that code below
if you timescale it though it'll no longer be accurate for play session time
there's like a realrealtime variable I think
lel
right! the while loop will execute until Time.time is larger than endTime
one more thing: what's wrong here?
IEnumerator RunForTime(float duration) {
float endTime = Time.time + duration;
while (Time.time < endTime) {
transform.position += Vector3.up * Time.deltaTime;
}
}
i guess something with Time.deltaTime
(ignoring the fact that this is now a compile error, whoops)
No, that's okay. We want to move at a constant speed, no matter what the framerate is
(well, it will be okay once we fix the problem, at least!)
Time.time is ingame time. Time.unscaledTime is ingame time if Time.timescale were always 1 (which is useful if you want to time something while paused).
Time.realTimeSinceStartup is the actual number of seconds since game started, which is mostly useless
honestly i don't get it
some thing that trips people up a lot with delta time is units.
๐ญ
let's follow what the computer would do
also, I'll make a thread for this
okk ty
coroutine
thank you!! I was always wondering why unity scales fbx models to 100!
I think you can also just change the units inside of blender to prevent that
Remember values have no dimensions, so their units are implicit (eg in your head). Distance has units of meters. Speed in meters per second. Time in seconds etc.
deltaTime has units of seconds.
If you do position += speed, then you are adding meters + meters/second which makes no sense.
if you do position += distance * delta time, then you are adding meters + meter-seconds, which also makes no sense.
But position += distance, and position += speed * deltaTime are both correct
If you keep this in mind, you will never fuck up delta time
yes -- it's good to do dimensional analysis
dimensional analysis saves lives, and the american school system does a shit job of teaching it
i remember learning it in chemistry class
i remember my high school chemistry teacher selling condos during class
great realtor
terrible teacher
can someone make/does somoene have a tutorial for this video:https://www.youtube.com/watch?v=dHzeHh-3bp4&list=LL&index=5
the idea is that i need the pointer to show towards the target at the edge of the screen but for 3D thanks!!
โ
Series Playlist: https://www.youtube.com/playlist?list=PLzDRvYVwl53t6iznGWrD_QB66ZoIz2BHa
Grab the Project files and Utilities at https://unitycodemonkey.com/video.php?v=dHzeHh-3bp4
Let's create a UI Arrow Pointer that will point to a location in our world.
If you have any questions post them in the comments and I'll do my best to answer them...
what? isnโt that video a tutorial?
yhea but for 2d and i tryed it for 3hours to implement it in 3d
so a tutorial of how to follow a tutorial?
youโre looking for something else I think
you want maybe something more like the compass in skyrim
i mean the idea of the tutorial
it is quite weird to have a pointer points outside the screen area in 3D
probably a direction on front of foot/body maybe better
they mean a tutorial of doing the same thing but in 3d instead, since that tutorial is 2d
pointers to the screen border in 3D are garbage
always super confusing
3D games use either a compass or a marker on a minimap
gimme a Crazy Taxi arrow any day
i want something like that
no you donโt
donโt enable him 
the underground 2 style arrow if you know what it mean
thanks
i only played NFS Underground 1
this is a crazy taxi video, not a tutorial :p
If you want an arrow that points towards the goal...
that is what i want
Lmfao
said it and clicked it after lol
skyrim compass is so much better imo
you might do something like goal.y = transform.position.y so that the arrow only points horizontally
ok then what should i do if you say it's a bad idea , but i want to implement it in this view
can the camera change angle
nope
then pointer at the edge of the screen would work
because this isnโt like full 3d
ok then you are with me here , how to do that 
define the point to look at. define the visible camera area. calculate position and angle of pointer. put pointer there
you need to define the world space bounds of what your camera can see anyway for lots of things in your game
you can get the bound by viewport to world point then to screen ray
not sure if there is better way
might as well do it now
I'm pretty sure this would be identical to making a cursor in a 2D game
itโs just awkward because 2.5D at angle. Heโll need to define a plane of the level or something
hello guys, I'd really appreciate if someone would help me with this one
yeah, Plane.Raycast would make it easy to test where in the world a screen-space point corresponds to
im a newbie
but maybe viewport to world conversion will make it easy
in visual studios, after I add . to the code, it doesn't show me the list of options
does anyone know why?
!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
btw is there anything before the dot eg gameObject.
followed the tutorial and the arrow moves fine but not where it should go
then it isnโt going to show options lol
nah there is
sorry
but it doesnt show the options
like should I change something with the settings or something?
so follow the guide of configurate ide
im a newbie
the bot message
where is it?
ah th
thx
can someone help me with this part of configuration
im a newbie
you should not need to do any of this
whilst Im writing a code, it doesnt show me a list of options after i add a dot
you should be using the version of visual studio that is recommended to you by Unity
follow the instructions instead of..not following them
but do you know the reason why it doesnt show me a list of options
like it is the latest version
because your IDE is not set up correctly
no need for update
This is wrong.
Does "Visual Studio" not appear in the list of external script editors?
Select that. This will tell Unity you want to use that code editor.
Then click "Regenerate project files" and close Visual Studio
then double click on a script asset to reopen it
wow
it actually worked
thx man
I appreciate your help
im a newbie i know its frustriating to deal with us
๐
it's good.
I s hould've guessed you had a problem with the script editor setting given that you were asking about using an unlisted version
I see
does anybody know why my animation speed isn't changing even though "Flapping" prints true?
Your "adjust speed if" function always sets the speed
if the bool is false, the speed is set to 1
don't you want to only update the speed if the condition is true?
context please
VSCode? Unity? Unity Hub?
ohhh I see its cause these are conflicting right?
did you try to create a project somewhere weird, like program files
Yes, because adjustSpeedIf is defined incorrectly
It should not set the speed to 1 if its condition is false
Hello! Does anyone know how to make a player die (apply animation too) and respawn when falling for a certain amount of time? For a 2D platformer. Thanks ๐
ohh ok nvm thank you
you would want to add Time.deltaTime to a timer every frame that you aren't grounded
and when the timer gets too large, you triggger the death animation/respawn/etc.
the timer would be set to 0 every frame you're on the ground
(by "timer", I mean a float variable)
I understand the point but I don't really know how to do it
What part are you confused about?
where do I add Time.deltaTime for every frame that I'm not grounded exactly?
You'll want to look at the !logs
Update runs every frame
to do something every frame, you do it in Update.
Try to create a project, then check the end of the log file
hit windows+R to open the Run dialog
then paste that windows path into it and hit enter
this will open the logs folder
%UserProfile%\AppData\Roaming\UnityHub\logs
You want to see if there's an error at the end of the file.
It will probably be something like "EPERM couldn't make directory"
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
should i create object pool for particle?
Hey does anyone have a camera controller script that they are willing to share? Something like Kenshi or Mount&Blade where you move cam with WASD and can zoom in and out
you want info-log, I believe
kinda sounds like you don't have an editor installed
if you do, i'd reinstall it, then restart your computer
or maybe do those two things in the opposite order
why does my Transform layout look like this?
you have debug mode on
click the triple dots in the top right corner of the inspector and switch to Normal
Debug mode turns off custom editors and shows some extra properties
it's useful for when you want to do Evil Things, like switching which script asset a component uses
(sometimes I do that manually in text editor)
i want to add an interface component to the player through code based on which character is equipped the character stats and model are in a scriptible object but how do i do it for the interface
Quick question,
Functions must start with an uppercase, right?
Uppercase first letter of each word yes, known as "PascalCase"
Super, thanks ๐
hardModeGameManager = GameObject.Find("Game Manager Hard Mode").GetComponent<HardModeGameManager>();
is this or is this not the correct way to reference another script? In Start(), everything spelled correctly. NRE very very annoying.
yes, it is correct, syntactically, that does not mean it actually works as I've already told you
if the result is null then the game object named Game Manager Hard Mode does not contain a component of type HardModeGameManager
initialized as private HardModeGameManager hardModeGameManager;
The easiest and foolproof way of referencing is still making that variable serialized, and drag-dropping the object in the Inspector
Or have another script inject it for you if the object that tries to find it is a prefab spawned later on
It's the literal name of the script attached to the game object. I'll try reattaching I guess
btw if this line is generating a NRe then the game object Game Manager Hard Mode does not exist
screenshot the inspector of Game Manager Hard Mode
does it matter if the object is disabled in the hierarchy?
is it easy to make an assembly so I can use the internal keyword?
I have a function named IsGrounded(), when I call it, it returns true or false.
Is it possible to call this function in a if-statement?
I tried this but it didn't work:
if (IsGrounded())
{
// code
}
it isn't an issue of disabling it though, I watched it enable on the inspector when I launched the game
this is why Unity wrote documentation which you should be reading
it isn't because its disabled, I have the same functionality with another game object that has almost the same code and it has no issues being used the same way
If you can, just drag-drop this object onto your other script to directly reference the HardModeGameManager. Find is not needed here, and almost never is
bet?
I'll give it a whirl
Yes that works, as long as the method returns bool instead of void, and that there is a return statement in it for each accessible code path (eg. in an if statement, you would need to return in both the if and else parts)
you are correct but I don't understand why the same script with a slightly different name is working when used this way (disabled at start and enabled when the proper difficulty is selected)
script exeuction order
Thank you very much! :)
yeah I figured it out, I had an object with the controller script enabled at start when it's supposed to be disabled. That seemed to do the trick. Thank you!
In the function, I check if the player is touching the ground using a Raycast;
Physics.Raycast(transform.position, Vector2.down, groundedCheckDistance);
Can I use return Physics.Raycast(...) to return true/false?
now they both activate at the same time when condition is correct
Yes! As Raycast also returns bool you can directly pass it to return
Hmm, I get this error when I tried it:
Since 'PlayerController.IsGrounded()' returns void, a return keyword must not be followed by an object expression
You need to make the method return bool, not void
so change void to bool
private bool IsGrounded() { ... }
that is the return type of the method
Ah, now it works!
Thank you once again :) ๐
Getting this error ```Severity Code Description Project File Line Suppression State
Error CS1061 'Mover' does not contain a definition for 'MoveTo' and no accessible extension method 'MoveTo' accepting a first argument of type 'Mover' could be found (are you missing a using directive or an assembly reference?) Assembly-CSharp W:\Game Dev\Unity Projects\RPG Project\Assets\Scripts\Control\PlayerController.cs 49 Active
using UnityEngine;
using UnityEngine.AI;
namespace RPG.Movement
{
public class Mover : MonoBehaviour
{
private NavMeshAgent agent;
private Animator animator;
// Awake is called when script is first loaded
private void Awake()
{
agent = GetComponent<NavMeshAgent>();
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
UpdateAnimator();
}
public void MoveTo(Vector3 destination)
{
agent.destination = destination;
}
private void UpdateAnimator()
{
Vector3 velocity = agent.velocity;
Vector3 localVelocity = transform.InverseTransformDirection(velocity);
float speed = localVelocity.z;
animator.SetFloat("forwardSpeed", speed);
}
}
}
Hello Guys , I am facing a problem in developing my runner game for mobile, and this problem is that I want to make a generator for infinite levels that do not end, like runner games, so that you know more about the thing I mean. I mean, I do not want to make infinite tiles. I just want to make a generator that creates stages. Whenever you complete a stage, he gives you another stage, but with different things, meaning the obstacle will be in a different place, and the money is in a different place, and so on, and I want automatically. I mean, whenever you complete a stage, he gives you another different stage, and changes the number of the stage or the number of the stage. For example, when I finish one stage, they are given a stage. Randomly, he writes number two and notes: I never want the stages to be the same.
It may be referring to another one, do you have the using RPG.Movement at the top so it locates the right class?
yes
Where's your move to function that accepts a first argument of the type Mover?
The move to function shown takes a vector 3.
It's a MoveTo function that accepts an argument of the type Vector3. The error message is in my PlayerController script on a line that says GetComponent<Mover>().MoveTo(hit.point);
and hit.point is a Vector3
Hover over the Mover in the code that produces the error and make sure the tooltip shows it's from the right namespace.
Or you can just Ctrl+Click that Mover to go to its definition
Error said you tried to pass it a mover object
Show us where you're calling this function
{
RaycastHit hit;
bool hasHit = Physics.Raycast(GetMouseRay(), out hit);
if (hasHit)
{
if (Input.GetMouseButton(0))
{
GetComponent<Mover>().MoveTo(hit.point);
Debug.Log("Walk. Walk. Walk.");
}
return true;
}
return false;
}````
Guys I Have a Problem
Don't we all . . .
What you're looking for is called procedural generation
Should be line 49 of the player controller script
It's not easy to explain quick in a discord message but look up "unity procedural generation" and see if that helps as a jump off point
It's this. This is line 49
Yes, exactly how I will do it
GetComponent<Mover>().MoveTo(hit.point);
@tulip stag #๐ปโcode-beginner message
Clear the error and try again. The error suggests that you've passed something other than a vector 3.
Yo! Quick question. I've done my player movement with a CharacterController. Now I want to do a health system (hp, damage, etc...). But I saw that the CharacterController only get collision while moving, this will cause big issues (I think). Is it better for me to switch to a rigidbody ?
ok
Ctrl+Click now
Wait how do I clear an error in visual studio
try this
GetComponent<RPG.Movement.Mover>().MoveTo(hit.point);
```force the compiler look for the class under namespace
The error is legit
dear god !
Character controllers dont have anything to do with health systems furthermore a rigidbody doesnt have anything to do with a health system either.
it sent me to a whole different script ... oh fuck ๐ญ
I think I messed up my project big time with Github
You would have to make a custom class for any health system , damage system, etc
But I need collisions to know if my player got hit. So it has something to do with CharacterController and Rigidbody ?
I tried returning to an earlier version and now it's all messed up I guess the mover script got duplicated
๐ตโ๐ซ
You can detect collisions with a character controller? And with a collider + Rigidbody
It doesnt matter which one you choose
They both have colliders
Yes. But the problem is that I saw that the CharacterController only recognise collision when Moving. But I could take damage while not moving
Maybe that is false, but that's what I saw therefore my question
The documentation says that yes^^^
Nice
But throughout my experience it seems to always detect collisions