#archived-code-general
1 messages Β· Page 313 of 1
the static event sending a reference to itself would be something id try to get away from. if something just wants to subscribe to a specific instance, and ignore all the other instances, the static event is gonna introduce more complexity. You're gonna have to know which instance you want anyways
But if you simply want to be notified of something happening with every single instance then i guess it works
although ive never needed such a thing
Appreciate the feedback. Since I have no formal education in programming I am often unsure how much pain my programming choices wil bring in the long run π
So out of interest how do static Actions replace the need for FindObjectsOf<Type>
Every time i change/populate a value here(SerializedFields), the domain reloads. Is this an issue, or is this expected behavior? i am using 2022.3.26
I just do not recall it doing this, up until now, in other projects. seems to be doing it everywhere now though
you cropped it out, but you're probably modifying the default values for a MonoScript so yes working as intended. Hopefully you don't think you're editing prefabs
I am just populating serialized fields in the inspector.
Its not 100% equivalent but in my case I just need the most recent safe area that my character traversed. So I could either:
a) cache all safeareas and then subscribe to each scripts own Action or
b) cache no reference and listen to the static Action that adds the most recent safearea as a reference.
Even though theoreticall you could call the static Action on Awake() on each safearea to get the all references. Sounds horrible though. π
technically you're populating default references for a MonoScript, which is what the MonoScript's serialized fields will be set to by default when you add it to a GameObject in the editor
Is there a way to set them to default in the code ahead of time? Without a Find/Set, etc. i mean more similar to float imAName= 2.0f; Basically, is there anyway to stop it from reloading the domain every time i set a serialized field value. Or, set is ahead of time in code so it only has to do it once as a group
you're not setting any serialized fields atm. You are setting default fields. You probably mean to create a prefab and edit its serialized fields, in which case you are doing it wrong and that's why it feels weird to you
Oh, **** Yes. thank you. Major brain dead moment. sorry you had to say that three times before it registered
This is a weird question so I apologize in advance if it bothers anyone.
I've never gotten far enough into developing a game to need to utilize Scenes.
I always thought the rule was "1 scene at a time", but after looking into it, I see that scenes seem to be just a collection of GameObjects, such that multiple scenes can exist in the one "World" at a time.
My question is, is Unity setup in such a way that there is always only ever exactly one "World"/"Universe" and we load/unload scenes into and out of it?
(The answer may be very obvious and justifable, but I'm more interested in any discussion that comes from asking)
Hello, I'm trying to create a wall-sliding mechanic for my character. To do so, I've created a minimal environment with just a ground tile and 2 walls to test it. I have written a script for the mechanic myself, however, the character just sticks to the wall instead of sliding. To fix that, I looked up a tutorial on YouTube which writes a completely different script for the wall-sliding mechanic. So I created a new project, created the same minimal environment, and copied the script from Youtube into it. The result is however the same, the character is just sticking to the wall instead of sliding off.
I can attach both scripts here, however, I'm starting to think it might not be a coding problem. But If it isn't, I don't know what else it could be since it doesn't seem like i'm doing anything wrong in the scene.
Checked the following?:
Rigid-bodies gravity
Physics Materials
Yes, all in order
Rigidbody & Box collider for the player,
Box colider & Wall layer for the walls
Ground layer & Box Collider for the Ground
Check the players position when they're on the wall. Is the position completely constant, or changing infinitesimally?
(Just throwing some sanity-checks at ya)
I did, it's actually changing sometimes, it will very slowly fall , but it takes breaks if you know what I mean? It will slide for 0.0002 for 2 seconds then stop for 0.5 seconds then keep going. The speed of the sliding changes if I increase the gravity scale of the character, however it remains inconsistent.
Interesting.
And you've added physics materials (since ur using Physics by the sounds of it) with the appropriate friction?
Might be worth testing with a frictionless material
Additionally, change whatever your players move speed is to some massive value and see if that shoots him off into space, or if he's really stuck in there (not too massive tho haha)
Booting up the project now to test that
I can't promise anything but shoot your script through and I'll have a look, if the tests yeild no fruits
What physics materials are you talking about? Honestly I was under the impression that physics are innate once you add the rigidbody + box collider
Also nothing changes no matter what modifications I make here
^^^ Wall Layer is set to Wall btw
You should be able to create a Physics Material and provide it to the RigidBody component of both the player and wall
Right-click in Assets or whatever, and select Physics Material, I think
how come your player controller don't have 100 lines of serializable 
can't find it give me a minute
So I'm new to Unity, and running into an issue that I'm not sure how to solve.
The view area for my player is the selected box here - the chat-like panel on the right side shouldn't have anything render under it, so I want to constrain the camera's render area specifically to the currently selected box.
I'm not sure how to do this exactly - I feel like using a render texture would have downsides? (click raycasts for selecting things not working? not sure if that's an issue to be concerned about or not).
But I'm otherwise not certain about how to deal with this issue.
I found an easier way of checking for ground/walls other than creating an empty game object by creating an invisibile ray around the character that checks for certain tags, i'll show you in a second
if you are using 2d, you can click on 2d then physics materials
yes I know you can use OnCollisionEnter but im too lazy to change it
i am making a tic tac toe game and i want to make it single-player
how can i add AI moves to it?
I've added the physics to the wall/player, played with the numbers, now the player just completely sticks to the wall
nvm ^^ it still slides slightly
Interesting, with 0 friction?
Feel free to paste your script
Yeah
Yo
it works now
wait
let me figure out what i just did
So, with friction 0, it doesn't stick to the wall, but it also doesn't slide, with anything > 0, it will just stick to the wall, so ig the problem isn't solved
Vector2 raycastDirection = transform.localScale.x > 0 ? Vector2.right : Vector2.left;
localScale? Oh, does that 'flip' 2D things?
But I think there might be a problem with it now
For some reason now the wall slide works properly for the first time ever
Howevr it only works on the right wall, and there is no difference between them. But I think I can fix that
Sweet, sounds like you've found something to investigate. Goodluck friend
Thank you, couldn't have done it without your physics suggestion, honestly I thought that was mainly a 3D thing, still got a lot to learn about Unity
You would probably need some kind of director or state machine that can determine available spots based on whats on the board already, depending on how challenging you wanna make the AI, you could have it pick a spot at random, or "score" spots similar to A* pathfinding logic (MinMaxing) and pick the spot with the highest score, though that could have a lot of games end in ties against players who are familiar with the rules of Tic Tac Toe, though there are probably more simple approaches online searching something like "tic tac toe ai C#" or "tic tac toe ai algorithm tutorial"
ok i will try that
TicTacToe has a lookup table for the most optimal move
i.e unless you dumb down your AI your games will always be a draw
i think then itll be better to have two types, one which selects randomly and one with minimax
Can someone help me? I am working on an Android multiplayer game project, and I am experiencing stuttering while playing the game. Is there any solution to fix this?
it always being a draw is incorrect. tictactoe is solved, if the AI goes first it can always win. maybe just have a random chance for it to select a random square (unless there is a direct win), otherwise it tries to minmax.
You're in the editor, not really a true performance test though your CPU time seems very high
Tris are fine, so your GPU isn't the bottleneck
Probably too much garbage being generated
Open the profiler and see
Window > Analysis > Profiler I think
I reckon it's GC issues
hi My problem concerns the rotation of my camera in my first-person game. When I switch to a second camera, I find that my camera doesn't rotate properly. I'd like my second camera to be able to change direction like the first
nvm prolly wrong channel
i just created a new project and tested the third person controller still i am experiencing the stutter
Whats in the third person controller
The update loop specifically
The best way is to profile it
(and on device rather than editor)
The same stutter also occurs on the device
You should use the profiler to see what part is actually causing a stutter, which I assume you're referring to a drop in fps since the video really didnt seem like its stuttering.
Before we can actually help you need to show a screenshot of the profiler or post your update loop
If you have narrowed it to your third person controller
{
GameObject removedLaneLeft = Lm.instantiatedLanesLeft[Lm.instantiatedLanesLeft.Count - 1];
GameObject removedLaneRight = Lm.instantiatedLanesRight[Lm.instantiatedLanesRight.Count - 1];
Collider2D leftLaneCollider = removedLaneLeft.GetComponent<Collider2D>();
Collider2D rightLaneCollider = removedLaneRight.GetComponent<Collider2D>();
Debug.Log("Function called, waiting for foreach loop");
foreach (GameObject i in items)
{
if (i != null)
{
bool isWithinBoundsLeftLane = leftLaneCollider.bounds.Contains(i.transform.position);
bool isWithinBoundsRightLane = rightLaneCollider.bounds.Contains(i.transform.position);
Debug.Log("Foreach loop reached");
if (isWithinBoundsLeftLane || isWithinBoundsRightLane)
{
Debug.Log("Speed changed");
i.transform.position += new Vector3(0, ((Speed + 5f) * Time.deltaTime), 0);
}
else if (i.transform.position.x == mlp1 || i.transform.position.x == mlp2 || i.transform.position.x == mlp3 || i.transform.position.x == mlp4)
{
Debug.Log("Cars Destroyed");
items.Remove(i);
Destroy(i);
}
else
{
Debug.Log("NONE OF CONDITION MATCH");
}
}
}
}```
My GameObject 'i' is gets destroyed occasionally which isn't the problem. But the problem is I face missing reference exception. For which I have added if (i != null), but this causes the unity engine to be freeze and gets in infinite loop ig
a problem is here
items.Remove(i);
you cannot remove from the source of a foreach. You need to use a plain backwards for loop
you cant modify collection is foreach
for (int i = item[max]; i > -1 ; i --)
u mean this?
Also there is abasolutely no point is just butting ou8t text messages in your debugs, include some variable data so you know what is going on
items.Length or Count, but yes
okayyyy
i >= 0
i is int
you will need some thing like
GameObject go = items[i];
then replace all i references with go
this is definitely not Code General territory
got it
wdym
beginner code question
these are very much beginners questions
i m getting this error Random' is an ambiguous reference between 'UnityEngine.Random' and 'System.Random' at this line "float randomnum = Random.Range(0f, 90f);" i made this a half year ago and only now it gives me this error
put using Random = UnityEngine.Random at the top of your file to fix that
is dashing just a player sliding really quick across the world grid with cool animation?
is really not working
unfortunately i can't help if you don't give any more info lol
A 'using namespace' directive can only be applied to namespaces; 'Random' is a type not a namespace. Consider a 'using static' directive instea
the syntax of using XX=AA.BB.XX is using alias not using namespace
show your code
i figured it out thanks
hey guys, have a problem. I started making settings screen in my game and want to provide standart set of settings for player. The problem is
Screen.SetResolution(640, 480, FullScreenMode.ExclusiveFullScreen, new RefreshRate() { numerator = 60, denominator = 1 });
This function literally does nothing. It just doesnt changes resolution. I know that is shouldnt work in editor, so i test it in build. I tried few versions of unity and it doesnt helped.
Are you sure the code is actually running?
Have you verified it with logs?
yep
you should generally only set the resolution to one you know is supported by the screen, you can fetch those from https://docs.unity3d.com/ScriptReference/Screen-resolutions.html
the supported refresh rate might be slightly different for example
aside from that, have you looked at the logs from a build?
Oh, actually code was running in editor, but not in build, your question helped me to realise it and i fixed the problem! thx a lot!
anyone know a good source for geometry maths? I want to know which of 2 lines is most parallel to another which the slope check could do though the slope is infinite as it becomes vertical!
chatgp(mention it not) suggests slope comparison and then struggles with my mention of divide by zero case!
In mathematics, the dot product or scalar product is an algebraic operation that takes two equal-length sequences of numbers (usually coordinate vectors), and returns a single number. In Euclidean geometry, the dot product of the Cartesian coordinates of two vectors is widely used. It is often called the inner product (or rarely projection produ...
Vector3.Angle or just the dot product
(Dot product will be more efficient but Angle is more understandable)
yes thanks - dot product is good
Just make sure you normalize your vectors before comparing dot products
I always forget dot product when not doing lighting
advanced:
since the "end point" of every unit direction vector lie on a unit circle (if they are start at origin) that means you can do a nearest neighbor search to get the closest point==closest direction
true dat
Do you know if I can create the name of an instance based on the value of a variable? I'm creating a websocket server for my game and I want to use instances of a "game" object to manage each game in progress, and to differentiate each game I wanted to know if I could name each instance of "game" with its ID which is a value defined by the player .
You can do whatever you'd like - but using the names of GameObjects is probably not a great way to do things
You should probably store that information in a custom script instead.
What do you mean? Because I want to create a class that manages a game, and then create as many instances of this class as I have games in progress.
Do you mean make a Dictionary with the name as key and the " game" object as value
Yes that makes sense. So what are you actually asking I guess?
If that's possible? Of course.
no I wanted to know what was the best way to access each of these instances? because at first I wanted to give each of the instances a different name using the game ID that the client uses to create the game, but apparently I can't do that, so what should I use, a dictionary? something else?
Sure a Dictionary works fine
OK, but how do you modify a value in a specific instance, since they'll all have the same name?
You can also give them whatever names you'd like, but that in and of itself doesn't particularly help you access them. It depends on what your access patterns will be like. If you'd like to access them by player ID or something then a Dictionary makes a lot of sense
the name is irrelevant. You use instance references (which would be stored in the Dictionary)
why would they all have the same name if that name is being supplied by the players
do you not know how to use a Dictionary?
because apparently I can't use a variable to name an Instance.
i can do :
game = new Game();
but i can't do something like :
GameID = 1
"game"+GameID = new Game();
Use a dictionary
myDict[GameID] = new Game();```
but you can do
Dictionary{string,Game> games;
...
games.Add(GameID, new Game());
Ok I'll look into using a dictionary, thanks for your help!
I'm just wondering how you think you were going to create a WebSocket Server without using dictionaries? It seems like this is new to you
Yes, I've never really used a dictionary, so I don't really know where and how they can be used because I only learned them in school in python to count the number of different items in a store XD.
Reset() on a ScriptableObject is supposed to be called as soon as it's created and when the reset button is called, but I'm having a problem where it never calls when I create it
#if UNITY_EDITOR
private void Reset()
{
string assetPath = AssetDatabase.GetAssetPath(GetInstanceID());
string fileName = System.IO.Path.GetFileNameWithoutExtension(assetPath);
if (string.IsNullOrWhiteSpace(fileName)) return;
itemName = fileName;
Debug.Log("i just reset earth");
}
#endif"```
also i'm trying to redo the multiplayer of my game, which was made in php and could only contain one game
Put the log at the first line
You have an early return that might be running
oh yea i forget that
oh wait
u just made me realize the mistake
I looked at the return and it's checking the wrong string
thanks bro
Is Awake after or before Reset()?
Look at the chart here https://docs.unity3d.com/Manual/ExecutionOrder.html
(before)
Thanks, but I've seen Awake get called again when creating the file and clicking enter(saving it) but the log had [Worker0] in it
It's quite a confusing situation
I'm just trying to make the string itemName become the fileName upon creation and saving
#if UNITY_EDITOR
private void Awake()
{
Debug.Log("Item just created!");
string assetPath = AssetDatabase.GetAssetPath(GetInstanceID());
string fileName = System.IO.Path.GetFileNameWithoutExtension(assetPath);
//if (string.IsNullOrWhiteSpace(itemName)) return;
itemName = fileName;
Debug.Log($"And it's been called [{itemName}]");
}
#endif``` Awake is when I create the item immediately, then when i give it name and save, it becomes in this state [Worker0]
Couldn't you just do itemName = name;?
fileName?
AFAIK yes
(in fact, itemName seems kind of redundant since name exists)
You could also just make itemName a property
public string itemName {
get => name;
set => name = value;
}```
then you don't need to serialize any extra data or worry about this reset stuff
hmm, it only works as a property for me
"A field initializer can't be Object.Name"
Maybe show what you had attempted to do to generate the error.
I tried initializing it as the value
public string ItemName = name;```
That's not correct
A property would be written like this
Well making it a field gets you back to square one
I guess an understanding of your goal for this might help
yea
What's the reason you need it to be a separate field?
I'm trying to make it that as soon as u create an item with a name, the item name gets initalized as that name, sometimes it helps being more effiecent
Right but why does it need to be a field and not just a property?
Can that property's value be changed?
I never did a property like that before so
That's the standard way to make a property
oh yeah ofc it can lol
What the purpose of this itemName variable?
It's what's gonna be displayed in the game UI
Everything you are saying leads me to believe this is ideal
So how do I make that serialized in the editor ?
Not sure what you're intending but the game ui should just be able to access the name property of the reference object.
It's already serialized
because name is already part of the SO
I meant the property
Are you just trying to make it visible to the inspector?
Why do you need the property to be separately serialized
what benefit would that have?
I meant showing it in inspector
Well it would be the filename
But if you want to show it in the inspector you could use a custom editor or NaughtAttributes
I do have a custom editor
and have a callback that changes the filename
Ok, I fixed everything
Sorry for the late reply, but I found a better solution than my super/sub-class structure, so I don't need help with that problem anymore. Thanks anyways!
But you're probably right, if I really wanted that to work I'd most likely need to make a custom inspector (which isn't really worth it).
It's not worth it tbh, I just removed all the initialization thing, it's not even important now that I look at it, it saves a 1 second of typing and I put 2 hours into this
Hey so is there anything I can use that has the read/write performance of a normal array but the ability to manage the memory manually of a native array?
yeah thats the native array I am using
the ability to manually manage the memory lifetime is incredibly useful, but it seems to have slower read/write?
You're meant to use it within the job system generally
with the burst compiler the access should be quite fast
yeah im using it within a task
task != the job system
unsafelist
oh wait really?
no safety check
I didnt know that
btw i didnt brenchmark it with normal c# array (though you cant still use normal c# array in job system), you can test the i/o per seconds by yourself
ok
is there an array alternative to unsafelist?
unsafelist is just a wrapper of pointer+length+capcaity (c++ vector), nothing more than that
ahhh ok
access the element by .ptr[] to bypass the indexer, the indexer is pretty annoying
!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.
https://gdl.space/utebizopoq.cs <-- script
script stop reseting the first dash cooldown for some reason
When I Destroy a (child) game object on an instantiated instance, then instantiate a new instance - the new instance seems to not have the game object... is that normal?
For background - I have a dialog popup that has a "click catcher" that I have to move out of the hierarchy of the dialog (because of raycast catching conflicts with a component in that dialog). When the user clicks on the "click catcher" the dialog destroys itself, along with the click catcher.
When I instantiate another dialog - the new one doesn't have a click catcher.
Sounds like you're actually destroying the click catcher on the prefab
Yeah I'm uh.. not sure how though.. I can paste some code if that's helpful
definitely yes
// screen that instantiates these dialogs
FtueItemRenderer fir = Instantiate(FtueItemRendererPrefab, transform);
fir.Show(...);
// FtueItemRenderer
public void Show(...)
{
...
SimpleCancelDialog.Initialize(Hide); // on pointer down callback = Hide()
SimpleCancelDialog.transform.SetParent(transform.parent);
}
private void Hide()
{
...
UnityEngine.Object.Destroy(SimpleCancelDialog.gameObject);
UnityEngine.Object.Destroy(gameObject);
}
where does SimpleCancelDialog get assigned though?
SimpleCancelDialog is basically a full screen image with raycasts on that calls the callback in initialize
it's in the prefab
and what object is this script on?
and on the screen that creates these prefabs, it's linked to .. the prefab, as usual
little noisy screenshot, sorry - but the "screen" that's instnatiating these is "GameRenderer", and the prefab is under my mouse and .. correctly linked to the prefab
SO it's assigned to another prefab?
or it's assigned to an object inside the FtueItemRenderer prefab?
the latter
Why is this necessary?
UnityEngine.Object.Destroy(SimpleCancelDialog.gameObject);
UnityEngine.Object.Destroy(gameObject);```
Shouldn't the second line implicitly do the first?
basically FtueItemRenderer "takes care of itself" and has it's own cancel click catcher thing... but for other reasons, I have to move this click catcher out of the hierarchy (I'm using a 3rd party unmask component which does some kind of messed up things with the unmask)
if SimpleCancelDialog is a child of the FtueItemRenderer?
I see
SimpleCancelDialog.gameobject is out of the hierarchy of this object here
since it's been moved to the parent
does that happen in Initialize or something
yeah, in Show()
oh right SimpleCancelDialog.transform.SetParent(transform.parent);
it becomes a sibling
aye
I can't tell from the context so far. I would expect that to happen if somewhere FtueItemRendererPrefab gets reassigned
I can video it if it's confusing.. .there's kind of a lot going on with this hierarchy and prefab and stuff though, I'm trying to pare it down to the minimum reproduceable code
maybe that's happening by accident somewhere
lemme snap a quick vid while I click around a bit.. standby
None of the Odin type "Custom Inspector" tools seem to support NetworkBehavior I am currently just trying to get a collapsible list of SerializedFields
they have all failed once MonoBehaviour becomes NetworkBehavior
this also includes NaughtyAttributes. Thre is a slight possibility that i messed up my test of NaughtyAttributes, i will test again later, but i am sure the others did not work. the only one i did Not test was Odin, since they have a wacky license agreement. I buy the thing just so they can inform me that i have to pay them a percentage if i make more than X $. I call BS. so, they remain utilized
So basically - FtueItemRenderer prefab has a "ClickCatcher" GO of with SimpleCancelDialog on it - i instantiate these as little .. you know, full screen FTUE dialog helpers.. any click on it dismisses it. The first one that gets instantiated correctly moves the ClickCatcher up and out of the instantiated item's hierarchy.. then when it's dismissed, both the ClickCatcher and FtueItemRenderer get destroyed.. but when I instantiate the next one (again from the GameRenderer)... this 2nd one doesn't have a ClickCatcher on it..... and I don't know/understand why
I mean, I could have the game renderer "be aware" of the cancel dialog GO and destroy it, but that feels hacky - the game renderer has enough shit going on already (look at all the serialized fields π€¦ββοΈ).. even in spite of my best efforts at components that take care of themselves
perhaps I should be using something in https://docs.unity3d.com/ScriptReference/PrefabUtility.html ?
I need some advice with how I should load and unload objects.
I have about 11 zones that I am not able to separate in the hierarchy.
If the player is in zone 1 I only want to load objects in zones 1, 2, and 5.
If the player is in zone 2 I only want to load objects in zones 2, 4, and 7.
etc.
What would be a good way to set this up? I thought about using tags for the objects in each zone, but I think searching objects by tag is laggy.
I also thought about creating a script that searches for every object by tag, then stores the references for later use. This would cause a large amount of lag at the beginning, but should be fine after right?
How would tags help at all? If an object is not loaded, it doesn't exist to have a tag.
When you talk about objects being "unloaded", presumably you are talking about either:
- Using the Addressables package to dynamically load objects at runtime
- Using additive scene loading
tried to add in occlusion culling to my game, all it did was hide everything i couldnt see from behind.
every single wall, any tile that does not have transparency is both occluder and occludee, the parameters are default. both because i dont know what they mean
doesn't seem like a code question
(also not sure what the actual question is)
i dont know where to post this
ah alright
I am using the .SetActive(true/false) to "load" and "unload" objects, I am not sure if this is the correct terminology. If the objects had tags I could search for them, then load and unload them when needed.
You're talking about pooling
You should google object pooling for the common patterns
dude thank you, this is what I am looking for.
That does not load or unload anything. Tags are not the way. Just maintain your own list or set of the items as you spawn them.
And yes this is called pooliong
how would one go about fixing a rare case like this? the player is stuck between two walls, and obviously can't jump since they're not passing a grounded check. Curious if anyone else has encountered something like this and how they went about solving it.
most games just have a "is considered airborne but not actually moving" check + timer (like 5 seconds or so) that respawns them somewhere on the map since it's a rare case, similar to falling out of the map and getting teleported back on somewhere
although some games just actually softlock you and you have to reload from checkpoint / lose / whatever
ahh never thought of that, that makes sense. Thanks!
Hey, my game is taking awfully long to load when hitting the play button and is then stuck in the completing domain part.
I tried to profile it but I can not figure out what scrip(s) cause this giga spike π
How can i make a plane 2 sided in 3d?
Right now you can only see the material on one side of the plane
To add onto Nephrens point, one game I can think of in particular, Overwatch has a similar check but adds a small amount of directional force so even if you manage to get stuck somewhere, or find a ledge you shouldnt be on, you will eventually "slide" off it when the force adds up, though they may do that more for gameplay reasons than collision limit reasons
Not sure if itll help, though you can try changing the bottom left from "Timeline" to "Hierarchy" which should let you see the functions stack that may be contributing
make a new material and change its render face to "Both"
Ohh
oh thats an interesting way to do it, im not sure that would work in my specific case since there is really nowhere to slide to, but that definitely does sound like something worth implementing
Mine does not have that actually
ah my mistake, it looks like you're using the standard render pipeline and not URP. I'm not sure how you'd do it in the standard render pipeline
gotcha
I am using a rigidbody for movement in unity, but the player is sliding down slopes and moving up them super slowly, I have just created a method that detects the platform the player is on, and the angle of the platform. How can I adjust the velocity of the player based on the normal of the platform they are on? I tried rotating the input velocity but that didn't do anything. Here is my code: https://hastebin.com/share/ucekeqataq.java
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
How expensive are the "TransformDirection" and "InverseTransformDirection" commands? I use them about 4 times in a single fixedupdate for one of my components.
Not ridiculously expensive. You'd need a lot of calls to start to notice it.
Hey guys, I have a question. It's not a code or Unity related question per-say but I was wondering for those who have worked with databases within Unity, how have you handled the client-server architecture? Right now I have created a WebAPI for my project and while I have Unity hooked up to the WebAPI, the API is using localhost at the moment. I was wondering if there are any free ways of hosting that API/database so perhaps a small team could access the API/database remotely?
Cloud platforms offer free tiers, GCP and Oracle Cloud have forever free VPS that's probably going to be sufficient to host your stuffs.
Alternatively, do you really need all of your team to remotely connect to the same backend? If not, have them host it locally on their own machine.
I need help with a unity problem that I have dm me @everyone
I need help with a unity problem that I have
That ping does not work, thank goodness, but did you really intend to ping over a hundred thousand people?
Just ask your question
also don't cross post
That could actually work and be easier, would you still be able to update the build this way? So for example, adding new data/tables and having that update once the build is released. Or would I need to keep the server database in sync with a local/embedded database?
Are you trying to have your devs connect to your production backend during development?
Because uh, that's a terrible idea.
That's fair, I can see the implications with that. How would you go about handling that? Would you just have each dev have their local database running on their own local server?
Having a deployment guide for each dev to deploy the backend on their own machine is one option
Oh for sure, you can have both a testing and production database. That's what I intend to do
But containerization like Docker is made to solve this problem, you just build a container and have devs run it.
Yeah, make a container that runs the dev environment
Make devs use the container
On production you can use the same bindings, now the app just connects to a prod container
Do I have to pay to host the docker container?
Awesome, I was thinking about a set up like this. This will make things a lot easier. Thanks guys π
What the docker container does is help you reduce complexity of development by having it be a packaged self-contained environment that anyone can deploy anywhere regardless of host machine.
No longer "works on my machine"
You can think of it as a virtual machine with everything you already set up, and the user just needs to boot it.
The cool thing about it is that the app that gets developed can use the exact same API calls because the production container will be the same container, but with a different environment handling whatever is needed on production side of things.
The app is non the wiser
I haven't worked with docker but I'm aware of what it does and the benefits but I thought you needed to pay for the hosting. Since I don't then I think that would be an ideal solution. I can run two docker containers for a testing environment and a production environment
Not even that, you can just send the Docker file to dev and the dev runs it locally on their own machine, the same machine that's doing their Unity stuff.
Awesome, thanks π
That FromTo rotation looks wrong, is it drawing the correct ray? I would also turn off gravity and handle it manually if doing a custom rb movement
The ray its drawing is correct, its straight out from the surface the player is standing on.
Whats wrong with the FromTo rotation?
that looks like the normal of the slope instead of where the movement should be going as a result of standing on an angle
The ray isnt drawing where the movement should be going
https://hastebin.com/share/enikuzuxiy.csharp why does it stop on first attack, swing 2 and 3 bools are never set to true i followed a tutorial btw
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Assuming the code is exactly as in the tutorial, you probably missed something in the animator or inspector setup
Here is the ray of the direction the player is currently moving
the code looks fine?
Hey, so I was thinking of making a Utility AI for an enemy NPC that executes actions based on probability. It would collect this information using a ray-cast sphere to understand what is around it. So Utility AI would be its brain and the ray-cast sphere would be its eyes. Has anyone dove into this for game development and can share anything that might roadblock me? planning on achieving this using C#.
Here is a video of the ray: https://streamable.com/ux8dgj
On the first glance, yeah. I don't know the tutorial, so it's hard to say without investigating the code and the setup thoroughly.
alr thx
Adding debug logs or stepping through the code with a debugger would help solve the issue. I'd double check that the setup is exactly as in the tutorial first though.
good idea i will do that
Well, this is a very abstract explanation. There are many way to implement what you described, so it's hard to say anything about roadblocks as well.
Applying the method to the velocity directly messes it up quite a lot https://streamable.com/0zudqv
velocity.x = Mathf.Lerp(velocity.x, inputVelocity.x, t);
velocity.z = Mathf.Lerp(velocity.z, inputVelocity.z, t);
you arent considering the y part here, which explains why its going slow upwards. When you rotate the vector you still need to use the vertical
So the full detail of the use of this:
Enemy NPC walking doing its patrols then when a player comes with in range of the detection sphere or starts shooting at the enemy NPC the NPC would evaluate what it is around it to use as cover or if the area it currently is has the most cover. The AI would first do a probability of it being hit by the player and if its in a high enough range it checks the better cover in its area or evade that higher probability of being shot and chooses the animation appropriate for that cover that it is under. Then would evaluate when its best to return fire to attack the player or advance towards the players last position.
The information it would receive would be from the sphere and give everything its own tag being a pillar or rocks or wall etc.
The AI would know the probability of each due to the position it currently is and what has the better coverage by giving each static object its own stats of being shot at if behind the cover and coverage of the NPC or player so it works for both the enemy NPC as a attack strat or defensive strat. It would also make its own probability using those base stats depending where it is and where the player was last seen.
Sounds like a plan. Can't see any obvious roadblocks, but there might be some that you discover during the implementation.
I just rewrote that to account for the y axis and also applying gravity manually but that makes me still slide down slopes. Here is my code now. Here is a video: https://streamable.com/q1lffb
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I fixed the gravity so the player nolonger slides down slopes, however, the player now goes up the slopes slightly due to the gravity now pointing to the slope. Heres the code. https://streamable.com/5oua4k
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i was watching a tutorial and i saw this guy make a float and he put {get; private set; } after the float name what does it mean and how and when do you use it
the gravity doesnt need to point in the direction of the normal
ye but i dont get what the point of it is
just for security?
you'll find answers and examples online if you google why. you can accomplish the same with methods but its just nicer sometimes to use a property
i did google i just dont see the point tho
il try looking more
theres really a lot of reasons that they are used, a simple example is just the basic one you wrote.
public float SomeValue {get; private set; }
it is publicly available for things to get (read) but can only be set (write) from within this class
Otherwise you need the java way
float someValue;
public float GetSomeValue() { return someValue; }
void SetSomeValue(float someValue) { this.someValue = someValue; }
properties should also be preferred over public fields so you have finer control over what can access your data and how that data is accessed. you should very very rarely use public fields
Ah im too tired rewrote my example like 3 times but now its correct lol
has anyone ever seen this error before:
BadImageFormatException: Format of the executable (.exe) or library (.dll) is invalid.
I get it when I try to export my project to iOS and it fails build every time. Tried reimporting all assets that did not work.
#π±βmobile for issues regarding building for mobile devices
If you don't declare an accessor, yes. The implied accessor is private.
Do I need to disable gravity if the angle returned is greater than 0?
wouldnt that make me hop down the slope
if you are handling gravity yourself at all, i would just disable it entirely and do whatever you want yourself
you want it to be 0 if on a slope you're allowed to stand on
You said to just disable gravity? https://streamable.com/pfvke2
well now you need to handle the gravity yourself..
π€·ββοΈ im still not sure why you are adding gravity in the direction of the floor in that first statement but really id just add debug draw rays for everything when making a movement system
im not even sure what your IsGrounded() logic is doing so i cant be certain that the else statement part is even running
The IsGrounded() logic is, shooting a spherecast down, and if it hits anything other than the player, than it returns true.
I think hit.normal is null if the player isnt grounded.
normal is a vector3, it cannot be null
so its Vector3.Zero?
instead of assuming what the code is doing, add debugs and check
yes though, a vector3 is by default zero
Instead of adding gravity in the direction of the floor, I am now applying it when the player is not on the ground, however, this causes the player to float up strangely on slopes. https://streamable.com/ctmpof
if (!IsGrounded())
{
rb.AddForce(Physics.gravity, ForceMode.Acceleration);
}```
The issue seems to be partly fixed when I decrease the distance of the spherecast, I discovered that from debugging the gravity application. https://streamable.com/8z2b42
https://hastebin.com/share/fiquboreti.csharp
how come it doesnt go back to 1st animatin and goes back to idle fast
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Question, if you edit the "motion" of an Animator's State through code during runtime, does that just affect the one object, or all objects using that animator?
put breakpoints
All.
I would recommend you to always apply the gravity, regardless of your player being on the ground or not.
This way, you wouldn't need to worry about the sphere cast being casted correctly
And in the real world, it's usually so that the gravity is applied to you not just when you jump or fly (do you?), but also when you walk and sit
Therefore, simply always adding the gravity to the bottom, which is, yeah, Physics.gravity = Vector3.up * -9.81f, is a great solution
That's all fine in theory, but video games do not reflect real life. The gravity being applied every fixed update is what's causing them to go down slopes over time. There is no need to fight the system, the gravity simply doesnt need to be applied if they can stand on such slope
Using real life would only be applicable if you're trying to make the best active ragdoll simulator. Which alone requires extensive skill
Alright, if the gravity is what causes them to slide down the slope over time, they might consider either applying the gravity when the object isn't ground, which should be checked with a sphere cast with a small radius, or applying the gravity in the direction, perpendicular to the slope, where it might also be great to change the rotation of the player to match the gravity.
This really reads like AI...
Rotation of the player to match gravity?
What are you talking about? Rotate the player to match the gravity.
Consider reading the 2nd option fully.
Does this perhaps make it more clear for you?
I have read it fully, and I am convinced there are either translation errors or some AI text used in some of your responses (not just from today).
This is the normal of the ground. Not gravity
I don't remember using translation in my previous response. Perhaps you're reffering to my bad English? Well, I'm currently working on its improvement.
What is it supposed to mean?
The arrow is supposed to show the gravity's direction, perpendicular to the slope in this case.
What bawsi is saying is that you would take the normal from the slope/ground that the player is standing on and use that as it's new up vector.
Which I believe is closer to what you actually want
The up vector isn't the same as the gravity
The line coming straight out of the ground is the normal yea. Gravity would just be a line pointing straight down regardless of the slope here.
The normal gravity is applied to the bottom, shown with the blue arrow.
The green arrow is the force you want to apply to the player in order it to move forward (or, well up? cause it's a slope)
The red arrow is the force I'm talking about. The force which is supposed to be applied perpendicularly to the slope's angle.
(there's even the 90deg angle shown)
There is no red force. This simply doesnt exist, that red line is just the negative of the "normal", since it's supposed to point outwards
The slope up vector is the same as the red arrow, just flipped basically.
Also that is very good art π
Of course it doesn't exist. That's what we're talking about all this time.
It should be implemented for the player not to slide down the slope, as it usually happens with the blue arrow
And the rotation of the player may also be changed according to this force, as I have previously mentioned here
This is, actually, what is usually done in this kind of games, when the player climbs different surfaces, like slopes, walls and ceilings etc.
Normal means the tangent + 90 degrees from a point in a line.
Tangent meanwhile is the direction that a point in a line is going to.
I see, so the perpendicular vector.
You can calculate tangent by:
lim -> Delta = infinite: arctan(y1 - y2 / x1 - x2)
Where Delta is the span between 1 and 2 and gets more accurate as delta goes toward infinity.
Also, how would you get a tangent from the point in a line, which is a vector, if the angle is supposed to be passed into the tangent function?
Normal is a direction. Not really a vector. Mathematically speaking.
Normal is passed as a Vector struct in unity but it has no magnitude (magnitude = 1) and you normally use it as a direction component.
To actually be a vector it must have direction and magnitude.
Well, I don't think the tangent is required to find the normal of the direction.
You dimply replace the x with the y
Hmmm I don't think that's correct.
Yeah.
Don't mention the image I sent. That was wrong. 
Real.
if you really want to work with Angles or Rotation structs, i happen to made two structs. 
Angle struct and SinCos. I made SinCos after feeling bad that i use about a ton trig functions per frame for one thing.
The correct way is this.
cos is the x and sin is the y.
/// <summary>
/// ΞΈ + 90Β°
/// </summary>
public readonly SinCos Plus90Deg => new SinCos(cos, -sin);
The x and y axes are replaced.
And so the angle between them is 90
How do you guys handle tracking of stats/ unlocking achievements on steam? I have been thinking about my implementation for a while but it seems not ideal.
On the one hand I want to store stats per stage in my game, but also stats for the whole playthrough. So I was thinking of something like this:
public class Stats
{
public List<Stat> StatList = new List<Stat>()
{
new Stat("ENEMIES_KILLED"),
new Stat("DAMAGE_TAKEN"),
new Stat("DEATHS"),
new Stat("GOLD_EARNED"),
new Stat("GOLD_SPENT"),
new Stat("DEPTHS_SURVIVED"),
new Stat("REVIVES_DONE"),
new Stat("REVIVES_RECEIVED"),
new Stat("ITEMS_CRAFTED"),
new Stat("ITEMS_REFORGED"),
new Stat("ITEMS_BOUGHT"),
new Stat("ITEMS_SOLD"),
};
}
public struct Stat
{
public Stat(string name)
{
Name = name;
Value = 0;
}
public string Name;
public int Value;
}
To hold all the data for the stats, and then a handler for everything with something like this:
private static Stats _depthStats = new Stats();
private static Stats _gameStats = new Stats();
public static void DepthFinished()
{
// TODO: Add current depth stats to gamestats and set new depthstats
}
But it feels wrong to me, I want to unlock achievements straight when the condition is fulfilled and not at the end of each stage/ depth, but also checking for x conditions and manually adding one if statement for each achievement always when a stat is increased feels wrong and inefficient. There must be a better solution?
It's just the sin = cos and cos = -sin. Could you, please, show how you would actually implement it via code?
Yeah, that was a typo
This is a surprisingly in-depth conversation for a problem that's somewhat basic lol
It's cause i love helper functions.
Would you be able to provide a basic solution for this somewhat basic problem..?
I'm enjoying it, ignore me! 
I love em too
This also comes with unity custom editor. Albeit ranged from -180 to 180. SinCos can't express entire rotations.
I also have angle struct and a property attribute. I might as well paste em ehre.
I have a Helper script with all the possible static classes like RectHelper, MathHelper, TransformHelper etc.
Someone really loves angles 
More like someone hate fucking with both radians and degrees at the same time.
And #ifs
It's mostly so i can copy and paste for Godot and unity.
Then i found out unity can't serialise readonly so i have to add that in too.
But well, why would you even spend your time writing literally the full Angle struct? π€
The solution was mentioned already. Take the normal direction of the slope, use it as the up vector as movement cross product. But to be fair there is multiple ways to solve slope issue.
Mostly, i want to just build in the helper functions instead of having a DegreesToRad or RadToDegrees. I'd just make more functions that just take the Angle.
And then after that that i use trigonometry a lot for controlling joints and added SinCos and use that instead (when using a singular direction value is not important) and added an implicit cast for Angle to SinCos.
Sounds damn hard
Is it? It's literally just a wrapper for a float.
Cause if that's the case, why people even use Vector2 instead of a (float x, float y)?
Alright, maybe, but 311 lines is like 
311?
missed "lines"
Also, this looks strange
public static Angle Deg360 => one_revolution;
public static Angle Deg270 => three_quarters_revolution;
public static Angle Deg180 => half_revolution;
public static Angle Deg90 => quarter_revolution;
public static Angle Deg45 => eight_revolution;
public static Angle Deg1 => one_degrees;
public static Angle Deg0 => no_rotation;
public static Angle OneRevolution => one_revolution;
public static Angle HalfRevolution => half_revolution;
public static Angle QuarterRevolution => quarter_revolution;
public static Angle EigthRevolution => eight_revolution;
I just did that because Monogame Vector2, UnityEngine Vector2, and even Godot Vector2 did that.
I'm not really sure if it makes a difference for a readonly static.
There's a multiple getters for the same value because i felt like it. I just wanted to express the same constant value in different measurements.
Deg360 = OneRevolution
Angle can go above 360. And below -360.
Well angle is a scalar quantity. My source lol.
How might one store some data between scene loads?
And how might one store data between game runs?
Using something like JSON
Cool - and that would be a suitable option for both saving state "quickly" between scenes, as well as the entire game state?
Both yeah. Saving the state between scenes is saving the entire game state.
Awesome, cheers(:
Hello
I want to make navmesh agent wander and target the player how to do this?
I'm beginner to navmesh agent scripting
Does anyone else have trouble with Visual Studio and creating new files in the Unity Project Explorer? Every single time I create a new file, VS will eventually freeze up and require me to kill the process. This happens in all Unity 2022 versions with VS 2022 and newest Visual Studio Editor Package. (NOT VS Code)
My workaround is to declare classes in the same file and then use the VS refactor "Move to new File" instead, but this is driving me nuts
Are you using the "Visual Studio Editor" package or the "Visual Studio Code Editor" package?
Visual Studio Editor
Okay just making sure because your original message says Code.
Ah yeah, sorry I just noticed now
Also when attaching the debugger I very often get a 30-60 second Unity Editor freeze before I can continue. Not sure if related. Ive tried reinstalling both
That's alright
Its not alright. I dont want to wait, and it didnt use to be like this
Well, it's always been this way for me
Ive been doing this for 12 years. It wasnt always like this π
restarting the editor works for me at times
Times change 
(problem solved)
I use this code for my scp173-like enemy, which chases after the player when the player doesn't see it
try if (Physics.Raycast(cam.transform.position, dirToEnemy, out hit, distToEnemy, 1 << groundLayer))
So why not Debug the parameters passed into the RayCast?
i will try that
Also, ensure that your ground objects are actually on the GroundLayer
is there a way to check the canvas a gameobject is on?
explain
"Is there any way to check whether the Canvas' GameObject is enabled?"
Yes, using yourCanvas.gameObject.activeSelf boolean
like ive got a gameobject on a canvas and i need to find the rect transform of the canvas so i need a referance to either its recttransfrom or its gameobject
It still doesn't make much sense
sorry im not very good at explaining
You want to access Canvas' RectTransform?
yourCanvas.GetComponent<RectTransform>();
ok, generally a Canvas is a Root object so you can use gameObject.transform.root to refer to it
youve got a GameObject UNDER a canvas right? as a child of the canvas? If thats the case you can either use GetComponentInParent<Canvas> or simply use an inspector reference
its like a grandchild of the canvas
does get component in parent still work with multiple children
Gets a reference to a component of type T on the same GameObject as the component specified, or any parent of the GameObject.
ok ill give it a try sorry for the hassle
Is the Canvas the root object?
not necessary, if the Canvas is on a Root game object transform.root will give you the RectTransform you want
Also that, canvases are usually the root
the canvas is on a organisational empty game object called canvases
this seemed to work tho
Canvas is a built-in Unity component, so if you decided to call an empty gameobject "Canvas" (without having an actual Canvas on it), you should lead with that when asking for help π
no yeah im still trying to find the canvas component but ive got all my canvases on another gameobject called canvases for the sake of organisation
then I would suggest you put a singleton on that root gameobject which holds references to the children you need
I was gonna do that but i wanted to use the amount of references on my singltons sparringly because having to many would make unnessary strings of referances throughout my code
better that than wasteful GetComponents
in your case it has to scan through the hierarchy which, by the sound of it, is unnecessary complicated
when you add gameobjects purely 'for organizational' purposes you are doing yourself no favours
is there a way to make folders in the hieracy then?
because i just struggle havign heaps of gameobjects lying around when im trying to find specific ones
no, but why would you need them?
because just say when my project gets more complicated and i have like 10 canvases then it would be helpful to have them under one folder or gameobject to make them easier to find
not saying id ever get 10 canvases
but i use it more for different cameras
there is this amazing thing that the brain can do, it's called 'knowing what you have done and remembering it'
ive got a pretty bad memory
well you will have if you never exercise it
you put the variable initialization into the Awake method
Also, I would advise changing staff into Staff
Hey guys! I have a problem. When I selecting font in dropdown menu, It's importing wrongly. Like this:
https://hastebin.com/share/segajiqiki.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
How to I make the player not slide down slopes?
constrain it's y position
Please, read the messages sent after that one
Anyone?
I have my PC game that I am trying to convert its input controls to VR. I'm confused on how to do that, since I've never done that before since I'm new to Unity. How can I do that?
https://hastebin.skyra.pw/cadopuqunu.cs
applying the gravity in the direction perpendicular to the slope causes the player to move slightly up the slope when jumping, due to the gravity pointing in that direction. Are you saying to apply both gravity and gravity again but in the direction perpendicular to the slope?
like this
This makes the player not slide down the slope, but now they struggle going up.
I'm going to try something rq.
i added minimax
though i do want to stop it from not letting the player to win to also letting itself win
like
in the first game it wins, but in the second game it blocks the players win even though it had crealy a chance of winning
my code for minimax is something like this
private int MiniMax(int depth, bool isMaximizing)
{
if(CheckWinner() != "N")
{
if (CheckWinner() == "D")
return 0;
else
return CheckWinner() == computerSide ? 2 : -1;
}
if (isMaximizing)
{
int localBestScore = int.MinValue;
for(int i = 0;i < 9; i++)
{
if(values[i] == 0)
{
values[i] = GetPlayerValue(computerSide);
int localScore = MiniMax(depth + 1, false);
values[i] = 0;
localBestScore = Mathf.Max(localScore, localBestScore);
}
}
return localBestScore;
}
else
{
int localBestScore = int.MaxValue;
for (int i = 0; i < 9; i++)
{
if (values[i] == 0)
{
values[i] = GetPlayerValue(playerSide);
int localScore = MiniMax(depth + 1, true);
values[i] = 0;
localBestScore = Mathf.Min(localScore, localBestScore);
}
}
return localBestScore;
}
}
public void Update()
{
bestMove = 0;
score = 0;
bestScore = int.MinValue;
if(computerPlays && computerTurn && CheckWinner() == "N")
{
for(int i = 0;i < 9; i++)
{
if (values[i] == 0)
{
values[i] = GetPlayerValue(computerSide);
score = MiniMax(0, false);
values[i] = 0;
if(score >= bestScore)
{
bestScore = score;
bestMove = i;
}
}
}
buttonList[bestMove].text = computerSide;
buttonList[bestMove].GetComponentInParent<Button>().interactable = false;
EndTurn();
}
}
I got it working. cs var gravity = Physics.gravity; var newGrav = RotateVel(gravity); if (SlopeCheck()) { gravity = gravity / 2; newGrav = newGrav / 2; rb.AddForce(newGrav, ForceMode.Acceleration); Debug.DrawRay(origin, newGrav, Color.blue); } rb.AddForce(gravity, ForceMode.Acceleration); Debug.DrawRay(origin, gravity, Color.blue);
Here is how it looks: https://streamable.com/jzlvt2
No, I'm saying to apply just the gravity perpendicular to the slope, drawn red in the image below.
Yes, it was actually meant to slightly move the player up the slope when jumping, and I also meant you to rotate the player, when the surface's angle changes.
If you don't want this kind of logic with rotation, consider returning to your previous solution, using either aSphereCast or Ray
Just be careful with using radiuses / distances
Looks great. You may want to just apply the gravity to the bottom when the SlopeCheck() fails
Also, probably consider not dividing the gravity values by 2
I was only dividing them by 2 on the slope because if you apply 2 gravity's the force is stronger. But now that you said to only apply gravity to the bottom when the SlopeCheck() fails, I don't have to divide them since only one gravity is being applied at once.
Right. Also, I forgot to mention it. How do you check if the player is grounded?
Consider using the OnCollisionEnter and OnCollisionExit methods to change the boolean isGrounded to true and false respectively. That's, honestly, the most reliable option.
I shoot a spherecast from the center of the player downwards. The sphere has a radius of 0.49f.
Silly question, why's the reason a modifier is changing the prefab and not the actual instance
Well, yeah, consider using the method I've shared in the previous response
What kind of a modifier?
If you have a reference to a prefab, changing it will, obviously, change the prefab, not a random GameObject somewhere in the scene
Just a float for the health
Because you are using the prefab reference instead of the reference returned by instantiate
Well, do you mean, you change a float in the Inspector?
Yes, well, it's supposed to change the UI but the UI is attached to the instance not the prefab so right now it doesn't change anything
Why should I use that instead of a spherecast?
Because it's much more reliable
Not really sure what you are saying here.
Me either.
How so?
Could you, please, explain the issue better?
Well, if you want your SphereCast to work properly, you will have to find a proper radius and its location.
By using the OnCollision methods make your collision be checked by Unity
This will almost always be much more accurate
Just make sure you check the collision with desired ground GameObjects, which should usually have a Ground tag
I just need to know how to call the instance rather than the prefab
Instantiate returns the instance
Cache that reference being returned
var instance = Instantiate(prefab)
Hi im trying to resize the children of paisagemRight through script
I tried 2 ways that appear in the 3 and 4 pic and it happens the result in pic 1 does anyone know why those wireframes appear with the resizing and the actual object not?
As Aethenosity has mentioned, you have to spawn the prefab using the Instantiate method and get its returned value
T instance = Instantiate<T>(prefab, prefab.transform.position, prefab.transform.rotation, prefabParent);
Could you, please, send your code in a text form? !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 the gameobject is always there do i also have to instantiate it at the start or how would that work
I'm sorry, I don't seem to understand what you're saying. Could you, please, express yourself a bit better?
sure
Wireframes? You are talking about the blue lines, not the green ones, right? They usually appear when resizing the object.
Please, consider using one of the sites I've previously sent for the large code blocks.
im talking about the green ones yeah supossedly the object should be looking like them
ok mb
Not "mb". Use sites to send the code properly, if you want to get helped.
i never really instantiate the object i just have it on the screen
Well, the green ones are the objects, aren't they?
Now, could you, please, combine your responses and additional thoughts to build a full answer?
I cannot really answer a question I don't understand
I'm not sure if this is the right channel to ask it in but I wasn't sure which else to use
Is there a way in Unity to develop like a class diagram kinda thing that will generate a graph of how all the different components in your project connect? Like a model-view-controller diagram for Java
Absolutely. Unity has an experimental Graphview API
https://docs.unity3d.com/ScriptReference/Experimental.GraphView.GraphView.html
which you can use to develop any kind of graph view you wish
Then do gameObject in a script on that gameobject.
That will be the instance, not a prefab
I did that though
Then you were not affecting the prefab
Prefabs do not exist in the scene. Maybe that is the confusion?
then why does it modify the prefab and not the game object
it's a ontriggerenter2d
the is an issue with that specific line but im not sure how i am supposed to explicitly call the game object
It doesn't, it's just saying you never set a reference to the playerHealth
At least that is what it looks like
You cropped off the line numbers, which is super unhelpful
That is irrelvant. Your line 16 is not working as you think
Is player health on the same object as enmigo?
That would be suprising
And also, we have now proven this issue has absolutely nothing to do with prefab vs instance. If you had just shared your code to start with, we would have told you that from the beginning
The issue is that you need to look at the docs for GetComponent
No
Player health is on the player while enemigo is on the enemy
GetComponent returns a component attached to the SAME object, or null if it doesn't exist
I can just erase that line but the error still stays
Hey guys, i was wondering how you are loading game settings on game startup.
I found this mothod extention which executes the method before splash screen, or other times if wanted.
private static void LoadAudioSettings()
{
AudioMixer masterMixer = Resources.Load<AudioMixer>("Audio/Master");
if (masterMixer == null) return;
masterMixer.SetFloat("Master", -40f);
}```
The method does execute, AudioMixer is present.
But the volume is still 0 for the mixer.
I did execute this method later on by button press and it works like a charm.
Why doen't it set the volume on startup even tho the method gets executed?
Do you use another way to set the player settings on startup?
Well yes, you still have to set the reference
i made a jumping function and when i hold the jump button player should jump higher and i don t know why it isn t working.https://pastebin.com/aRJsUQjf
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
https://docs.unity3d.com/ScriptReference/Input.GetKey.html
Probably want to use that one
in HSR a turn based rpg similar to what im working on, attack dmg numbers appear with timing during the attack animations That are best practices for storing animations for a move and timing the damage numbers and effects?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class menegergry : MonoBehaviour
{
public SoundManager soundManager;
void Start()
{
DontDestroyOnLoad(gameObject);
}
void Update()
{
}
}
public SoundManager soundManager; doesnt work
!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.
lmao
bro really sent a screenshot
send the link, not screenshots
also what is the question here ?
like "doesn't work" what does that mean
soundManager does nothing here
ok, so your take away from the bot message was, im just going to ignore it and send a screenshot instead?
Ok and what does the error say?
idk object dont have component?
i think its supposed to be AudioManager
nope. that aint it.
did you create a class named SoundManager ?
but you reference a class SoundManager, where does that come from?
I'm pretty sure the error says that you do not have anything called Sound Manager
kinda irrelevant to the question
ill try again
**did you create a class named SoundManager ? **
class? name skrypt?
this is A class sure, but not the one I asked about
we are asking about this
this is referencing a class called SoundManger, did you create one?
ohhh no... I understand now, I thought it was similar to audiosource
so a have to do it otherwise
I think you need to !learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
Yes these are c# basics you should learn first before continuing forward.
Also for future this question go in #π»βcode-beginner
is there any performance advantage enabling isTrigger on a non moving object?
or is the performance only based on how many other colliders/triggers it needs to compare against in scene?
isTrigger has nothing to do with performance, it makes a collider a trigger volume instead of a solid collider
yeah which means that things like rigidbodies cant interact with it
so does this save any performance?
incorrect
Yes they can
wait really?
ohhh i meant directly collide
but i get what you mean yeah
i guess the comparison is still being made so its not factoring it out in any case
I mean. I would say performance is completely irrelevant
If you want them to collide, don't use ontrigger
If you don't and still want a physics message, then make it istrigger
ill explain my case from the root, i pretty much just have a collider on many objects so that once the player char walks behind it from the camera's POV itll attempt to fade it and make it transparent
You can disable layer interactions in the matrix too
i dont want to have like 200 objects with colliders in scene if possible but was wondering if isTrigger would somehow help lol
Yes, it will slightly increase the performance over the case when this object has isTrigger disabled, assuming it collides with the other objects, because Unity's physics will need to calculate those collisions. Enabling the isTrigger boolean makes those collisions be ignored.
they are on a different physics layer too though so them colliding with something was never an issue
just to confirm, this is for a feature of your game and not some weird attempt at culling non-visible objects, right?
If the interaction between layers is disabled, it will not make any difference in that specific case
I think the collision/trigger detection is the limiting factor here and not the displacement (math).
feature, so that once the player goes behind some obstacle the view isnt completely obstructed so i raycast against the collider and grab a script to fade in/out the object
and yeah dalphat pretty much, im not concerned about it colliding with anything at all, just purely in terms of which one is more performant (if any), but i guess because theres nothing in scene that will ever collide with these objects the impact would most likely be 0
If you're wanting to have multiple objects with colliders in the scene, the more common optimization would be to differentiate between static and dynamic bodies. Other than that, there's going to be some expense relative to the number of physics objects in the scene.
the best answer you get is profiling it yourself
yeah i think it comes down to just profiling tbh, not wrong about that
Just my experience with filtering out colliders, there is still some cost even if they aren't on the same layer
abit minimal at that
Got it, I'll have to profile it in that case and see the impact
Appreciate all the help!
I hate that dictionaries are not serialized
Maybe checkout the asset store for free inspector tools else they kind of are if you're referring to json - non unity.
List of structs with kvp -> Start -> new dict -> foreach struct kvp
Thanks I know about them, I just hate that it is not built-in, I use dictionaries as often as lists etc.
Oh god..Unity examples using k&r now?
whoever wrote that example code said "Fuck your C# conventions microsoft"
I am using a system of ScriptableObjects that hold default values which than get loaded in a MonoBehaviour, but there are some problems with this. Here is an example, maybe someone has a better idea on how to do this:
https://hatebin.com/mrmaiowhni
it might help if you explain what 'some problems' actually means
it's explained in the link
Looks like you need to look into Generics
does anyone know how to modify this line of code so that the value gets applied smoothly
rather than snapping
because lerp only works with float and not with vector3
lerp * 3
AnimalData<T> : ScriptableObject where T : Animal
List<IAnimalData>
I actually don't know the real issue, but usually if you want to contain the root of the constraint you usually also want to make an interface
I need to have a serializable List<AnimalData> somewhere to spawn any Animal.
Using an interface could work, just have to work around that Unity can't serialize interfaces by default.
Actually im kinda confused why it's not Animal that takes an SO of Animal data
your design on this is weird. If AnimalData exists solely to provide default values that Animal copies every time, put those fields into Animal and delete Setup and AnimalData
Animal then becomes an abstract generic class with an abstract CreateCopy method, and each subclass implements it
actually why do you have a copy there at all?
if (hit.collider.TryGetComponent(out PhysicsSurfaceData physicsSurfaceData))
{
m_audioSource.PlayOneShot(physicsSurfaceData.GetFootstepSound(force));
print("step taken");
//cam.position
}
how do I add bobbing to this (Im using charactercontroller)?
So a far as I am aware calling:
Singleton.Instance.PlayerScript;
Is not causing any relevant overhead.
What about:
Singleton.Instance.PlayerScript.gameObject;
Is the .gameObject in the end something where I should probably cache it instead referencing it through the singleton every frame if i need this in update? Or is it insignificant and I can do it like this in update?
no, it's just a reference so little to no overhead
this is like a micro-micro optimization
yeah, if i can i would like to do it like this to not have to set things up anywhere I need it
and cache it in each script where I do
Makes it nicer to have it one place
this is how I have my player object set up. You can only swap skins in the menus. So once the game starts my script only activates one of these models and the rest are inactive until you visit the menu again and can cycle through them (array for both model and matching animator). Is this a hit to performance? Should I do more than deactivate the unused ones?
why not just switch the spriteRenderer/ model? Not sure if that is a solution in your case
I have one Gameobject for the visuals of my character and depending on race etc i just switch a sprite
idk someone in here showed me this is how they do it.
it seems to work great but I have a beefy pc
Since they're all disabled you really wont have a performance issue but itll be way worse loading many of these compared to if you just had one
Not sure if what I said would be any significant improvement for performance, I assume it would be better there in some way but I would do it just for having your player more compact and readable
This also looks like hell to edit if needed.
https://gdl.space/qenaguqiso.cpp
hello i really dont understand the problem with my code basicly if i touch a trigger i should start a timer and the text get enabled for a few sec and then just go to setactiv(false) what can be the problem ?
You are using start here, which runs once. You need Update
Also subtracting by the timescale doesnt make a whole lot of sense, I assume you want deltaTime
ok i will try that
{
int playerCount = NetworkManager.Singleton.ConnectedClientsIds.Count;
int temp;
do
{
temp = UnityEngine.Random.Range(0, playerCount - 1);
}
while (m_SpawnPointIndexList.Contains(temp));
m_SpawnPointIndexList.Add(temp);
return temp;
}```
Hey i want for each player a random number bot every number only once. But my game is crashing what is false on this while loop ?
https://gdl.space/emilerayir.cpp
it works but now text dosent go away
nether does timer becomes false
how do I make everything but one script to just pause without breaking them?
Vague question. Time scale generally
whats that
I mean pausing everything but sounds to make it look like it crashed
Maybe consider not relying on luck to not select an already found item and simply maintain a copy of the collection - relative to what's available left. Remove items as you use them etc.
I want a Spawn Vehicle system for my cars for the first round that everyone get a random spawn point. When 8 players are connected I want that everyone get a random number between 0-7 but every number only given once
im thinking since days and i dont have a solution. i tried many things ..
https://hastebin.com/share/fiquboreti.csharp
how come it doesnt go back to 1st animatin and goes back to idle fast
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Trhis should work?
{
int temp = UnityEngine.Random.Range(0, m_SpawnPointIndexList.Count);
m_SpawnPointIndexList.Remove(temp);
return temp;
}
private void CreateStartPositionList()
{
int playerCount = NetworkManager.Singleton.ConnectedClientsIds.Count;
for (int i = 0; i < playerCount; i++)
{
m_SpawnPointIndexList.Add(i);
}
}```
```private List<int> ids = new List<int>(8); ``````cs
for(int i = 0; i < count; ++i)
ids.Add(i);
int index = Random.Range(0, ids.Count);
int temp = ids[index];
ids.RemoveAt(index);
return temp;```
thanks alot is working!!"
https://hastebin.com/share/fiquboreti.csharp
how come it doesnt go back to 1st animatin and goes back to idle fast
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Look at the code logically. You are subtracting from a value starting at 0. How will that 2nd if statement ever be true if the timer was true?
Is it possible to create realtime HDRP reflection probes at runtime? I'm noticing they don't budge from baked (the default) when changed from a script- is there some hidden fields I need to configure first?
anyone know how to fix this?
cause ive been trying to fix it for 30 mins and nothing is workin
Is there a way I can get a reference to a scene after loading it additively async?
I'm trying to manage multiple instances of the same scene
there is scenechanged event, not sure if it works additively though
it gives you old scene / new scene
nice
Would this work in the case where many load requests can happen in no particular order?
I want to trigger the load and have the reference in the same coroutine
https://hastebin.com/share/odufabuvol.csharp why when the first animation plays it is delayed and sometimes goes to idle'
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
There are two ways that I know of:
- if you have a gameObject that you know is part of the scene you're looking for, you can call gameObject.scene
- if you're adding scenes through code and need cross-scene access, you can have the script that spawns the scenes keep references to them.
you probably need to sub this on a DDOL
Hmm alright this might take some experimentation
I suppose it doesnt really matter what the order is as long as its the correct scene type and a unique instance,
I'll try working with the event since it gets called once after each scene loads
https://hastebin.com/share/odufabuvol.csharp why when the first animation plays it is delayed and sometimes goes to idle'
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
So when you select the Rect tool and then a gameobject, you can see these "anchor points" and rescale the object. Is there any way to interact with these anchor points in code?
Or helper functions that simulate behaviour?
Because really all they're doing is modifying the scale and repositioning the object.
i have a question
most likely using the Renderer's bounds
but the scaling would just be happening via the Transform
I have a text system that that types out a message letter by letter and plays a sound every X letters typed. Issue I'm having is that it seems to be framerate dependent and I'm not exactly sure why. I've tried formatting the code in a couple different ways but it still ends up with the same result. Here's the coroutine that handles the logic:
https://hastebin.com/share/niyezoquce.csharp
and an example of the issue is shown below.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
https://hastebin.com/share/omixidiyis.csharp
Can someone look over this and tell me what they think? I'm working on making an implementation for dynamically changing animation clips on a per-object basis, so I can play animation clips directly from file instead of having to shove them all in a mekanism tree, and dynamically modify animations as needed.
Am I doing this right? This should be creating an instanced override controller for whatever object calls it, which can then be modified without altering the animations of any other object in scene, but I'm new to working with these systems.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Would anybody that understands how to build a ghost time trials script and how to save/load that data be able to tutor me in voice chat for a bit? I think it would take us a very short amount of time and I have venmo for your troubles. I would appreciate the help. I can figure out the animations and all of that. I already have the scripts functioning. I just need to know how to get them to save/load properly as well as verify it all works. I already have a saveGameManager that works for levelData I just want to get it working for this ghost data now
I am experiencing an issue where the radar gun in my game is moving very jaggedly. Here is my code. https://streamable.com/aj9evr
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
https://hastebin.com/share/odufabuvol.csharp why when the first animation plays it is delayed and sometimes goes to idle'
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
your lerp is wrong
rewrite it , or Use MoveTowards
But I thought this was correct?
yeah but you're changing the startPos the lerp each frame
as you're setting the pos you're changing the startpos of lerp it doesn't know how to act
ooh, the same thing I'm doing for changing the color of my radar icons. ```cs
iconImage.color = startColor;
yield return new WaitForSeconds(0.5f);
float time = 0;
float duration = 2f;
while (time < duration)
{
iconImage.color = Color.Lerp(startColor, endColor, time / duration);
time += Time.deltaTime;
yield return null;
}```
This is in a coroutine
note how its start to end, rather than current to end
and the startCol only gets recorded in 1 frame then on the smoothing / over course of frames it stays same for start
I feel like I'm so close to having this solved. If anybody could tutor me for 10-20 mins while I share my screen I would send some tutor wages your way
Anyone have good resources on pathfinding in large open worlds?
Ya was just wondering if there was an inbuilt way to do it.
either do realtime mesh baking or you'd have to create a more localized custom grid/avoidance
Otherwise I guess I just do some math and move the position.
https://hastebin.com/share/odufabuvol.csharp why when the first animation plays it is delayed and sometimes goes to idle'
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Yea I figured, Ill have to likely to split the mesh into multiple sections then. Just wondering if there were any resources going into this more in depth that you might know of
no reason to split anything, just bake an area around the character each time it moves a certain amount bake again
Im using the terrain tool, are you able to split the mesh to bake only certain parts of it? I assumed you baked the entire mesh at once @rigid island
I've just applied this to my code and the positioning is working much better. https://streamable.com/ydv895
there are tools like area baking / volume baking
nothing to do with terrain
Learn how to bake a NavMesh on a small portion of your level. This allows much faster baking of NavMeshes on large procedural worlds, or on very large worlds. We do this by specifying a volume around the player and use the NavMeshBuilder class to collect the relevant sources and update a registered NavMeshData.
If you are taking this concept a...
Thats a big help thank you. I didn't know you could split it up.
I kept searching online for ways people set up pathfinding for open worlds so I was just hitting deadends when I shouldve looked into navmeshs specifically and I wouldve found answers much easier
yeah there are other ways to do this, but they require alot more work and code
also you probably wouldn't want to bake realtime for NPCs that are very far away
If I have three scenes, MainMenu, Area1 and Area2, and I've added them to the build settings in that order,
When I am editing Area1 and press Play, should I still be able to load other scenes?
Or now that I've added the scenes to the build settings, I must start from the first scene?
The build settings only decide what scenes to include in the build, their indices, and what scene unity would load on launch. Everything else is up to you.
yeah
I need a bit of help with something, I made a circular slider for a prefab thingy, and it works fine. it's just i can't get the knob to move with the filling.
wdym move with the filling
like, the knob isn't moving in a circular move, it's going around 360 degrees
can you show what you mean?
if (thomasModel == null)
{
LoggerInstance.Msg("Loaded Bundle Successfully.");
thomasModel = AssetBundle.LoadFromFile("Mods/AssetBundles/thomas");
// load thomas once
GameObject thomasPrefab = thomasModel.LoadAsset<GameObject>("Thomas the Tank Engine");
Vector3 thomasPos = new Vector3(-30488.41f, 489.5023f, 38069.4f);
// set thomas's scale
thomasPrefab.transform.localScale = new Vector3(20, 20, 20);
// set thomas's local position
thomasPrefab.transform.localPosition = thomasPos;
// test parent
thomasPrefab.transform.parent = va01system.transform;
// initialize thomas
modelInstantiator.LoadModel(thomasPrefab);
LoggerInstance.Msg("Thomas Should be waiting for you outside planet Vauldric!");
// set loaded to true
thomasLoaded = true;
public static void LoadModel(GameObject model)
{
Debug.Log("Object Instantialized!");
Instantiate(model);
}
does anyone know why i'm generating 2 objects instead of just one?
im trying to link the prefab as a child but it keeps making a parentless clone, and then an empty child-instance copy that doesnt actually do anything
they both seem to have the same data except the child instance just doesnt exist
do you mean the blue thing is rotating on the wrong axis?
yeah... I'm not good putting things into words
you want the blue thing to basically rotate on the 2d axis around the middle sphere
instead of rotating on the 3d axis
from what i can understand?
which part controls the blue part then
wdym by that? I assigne the bar to Handle Rec like a normal slider, there's no script to the slider.
the issue is the blue bars transform
How can I open 2 scenes at once, such that each scene has its own Scene and Hierarchy windows/tabs?
pretty sure the answer to that is "you don't"
also not a code question
If you could, please don't respond to my questions
why bother asking a question if you don't want a response to it?
They gave you the correct response. 1) not a code question. 2) you don't
No one else has a better response than that
Two scenes loaded at once share a hierarchy
I dunno about the scene window, I guess some custom editor code might be able to do it. But I've never seen it
Just you specifically, please
lmao what the fuck. just block me if you don't want to see responses from me?
No need to be rude to people. I dunno what your problem is, but, again, they gave you the right answer, and did it politely
I've had you blocked for a long time. But once someone has thrown an answer at a question, many would assume it has been answered, and don't bother giving their own. Now of course if your answer was incorrect, someone else might still respond... but regardless. If you could, please refrain from responding to my questions
yeah not my problem. good luck with whatever the hell it is you're doing though π€·ββοΈ
Well, I will also never be answering your questions either.
This is absolutely ridiculous. What a jerk
Thank you
if(clampedY == 1)
{
direction = FacingDirection.Up;
}
else if(clampedY == -1)
{
direction = FacingDirection.Down;
}
else if(clampedX == 1)
{
direction = FacingDirection.Right;
}
else if(clampedX == -1)
{
direction = FacingDirection.Left;
}
if(prevDirection != direction)
{
yield break;
}``` I have a coroutine and it is to move the player. If I have this logic in the code, It for some reason runs twice. Why would that be?
This cant be answered given the context, show more of the code and how you call the coroutine.
It was too long of code to send in discord so thats why I didnt, but let me try to get it.
{
var clampedX = Mathf.Clamp(moveVec.x, -1f, 1f);
var clampedY = Mathf.Clamp(moveVec.y, -1f, 1f);
animator.moveX = clampedX;
animator.moveZ = clampedY;
var targetPos = transform.position;
targetPos.x -= moveVec.x;
targetPos.z -= moveVec.y;
var ledge = CheckForLedge(targetPos);
if (ledge != null)
{
if (ledge.TryToJump(this, moveVec))
yield break;
}
if (checkCollisions && !isPathClear(targetPos))
yield break;
var oneWay = CheckForOneWay(targetPos);
if(oneWay != null)
{
if(!oneWay.TryToMove(this, moveVec))
{
yield break;
}
}
var stairs = CheckStairs(targetPos);
if(stairs != null)
{
if(stairs.UpDirection == new Vector3(moveVec.x,0, moveVec.y))
{
targetPos.y += .5f;
}
if(stairs.DownDirection == new Vector3(moveVec.x,0, moveVec.y))
{
targetPos.y -= .5f;
}
}
isMoving = true;
while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
yield return null;
}
transform.position = targetPos;
isMoving = false;
OnMoveOver?.Invoke();
}```
Use the !code links for long codes
π 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 some specific logic that's not in a loop is done twice, you're probably starting the coroutine twice. Adding some basic debug logs should prove to you if this is the case
I know the coroutine is being called twice. I have used some debug logs but I just cant figure it out. This handle update function is called from a statemachine update
if(clampedY == 1)
{
direction = FacingDirection.Up;
}
else if(clampedY == -1)
{
direction = FacingDirection.Down;
}
else if(clampedX == 1)
{
direction = FacingDirection.Right;
}
else if(clampedX == -1)
{
direction = FacingDirection.Left;
}
if(prevDirection != direction)
{
yield break;
}``` It is only being called twice when I have this in my code.
Probably some faulty logic with setting that character.isMoving because that's what would be stopping that coroutine from being called multiple times
Okay I can look into that. Thank you.
if prevDirection is different than the direction you exit the coroutine. and you do not set isMoving to true until after this code has run. so if you are moving in a different direction than previously you don't consider yourself moving and don't perform the move
Yes that is my goal. I want to emulate movement such as pokemon soul silver where you're only allowed to move in the direction you are facing but if you decide to turn a different way the character just turns.
Hi! Iβm really new to unity/fungus and Iβm having a coding issue- could I get some help on it? π₯²
- what is fungus in relation to unity?
- https://dontasktoask.com/
right so on one frame the coroutine is started, it performs everything up to the yield break on that frame, then the next frame the coroutine is started again because the character is still not considered moving but it is incredibly unlikely that you've let go of the input by then
also dont crosspost
tbh using coroutines here is likely gonna be more complicated than just using update
Sorry I just joined the server I didnβt know #2 and no one was answering me in the other channel
Well you didn't actually ask anything
And it had only been a few minutes
Would you reccomend me turn this into a regular function rather than a coroutine?
I got the error [00:21:19] Assets/Fungus/Scripts/Editor/ViewEditor.cs(140,99): error CS1501: No overload for method βFreeMoveHandleβ takes 4 arguments
Iβm gonna copy and paste my script in here just gimme a sec
You still haven't said what fungus is.
But your parameters are wrong
You passed 4 things, and apparantly it doesn't take 4 things
Ok lemme send u the script and u can tell me what to edit
How could I know.
For the third time, you haven't said what fungus is
Fungus is the unity add on for narrative games
its up to you, the only part that makes sense being in the coroutine is the while loop part. As boxfriend pointed out, isMoving isn't set until that section. Nothing is stopping the coroutine from being started if it yield breaks out due to an earlier section
Looks to be third-party. It would likely be best to ask them
Ok
I will try this and see if it works how I intend. I appreciate the help.
Unless this is the method you mean?
https://docs.unity3d.com/ScriptReference/Handles.FreeMoveHandle.html
I donβt think so, Iβm just gonna ask another server.
Ok, sorry I can't help.
Good luck
Remember to not ask to ask. Just go for it
I joined the server 5 minutes ago, I wasnβt going to understand the rules right away.
Oh, this is not a server rule. Just a general life rule
That is why the website I linked to has nothing to do with unity or this server
It is how you should approach all internet communications in forums/servers
Basically, get to the point. No one knows if they would be able to help you before you actually ask the question.
I use the Enemy class and WireEnemy inherited from it to control the movement of enemies. During the game, wire enemies can change to an ordinary one, so how can I change type of them to the Enemy type so that all the fields remain the same and the links are relevant?
WireEnemy already is an Enemy
It overwrites Move method
This doesn't really sound like a use case for inheritance
what do you suggest?
A state machine?
If the only thing different is how hey move... A bool?
if statement?
Composition enemy movement is its own component and you can swap it out with what ever you like
Argument 1: cannot convert from 'Interactable' to 'string'CS1503
How do i convert it to a string?
How do you want to convert it to a string..?
Im using it as a Class but i need to switch to a string once its done
right now its a Interactable currentInteractable;
but i need to convert to a string later on
what does that even mean, what is an Interactable and what would it look like as a string
cause if i switch it too public string currentInteractable
i get a bigger error
a Interactable object in the game
define a sting path property on your Interactable class/struct/whatever
or just clone it if possible
you can just directly reference the prefab from inspector, instead of using resources here
this will use resources.load every single time you want to instantiate an interactable
so I have a unity timeline and i want the last animation played on the timeline to keep on repeating, how would i do that? thanks
why this part of my script works with one client, but not several? If a client sends the ID 123, the game 123 is created and if this same client sends back the ID 123 the server tells it that the game already exists, on the other hand if another client sends 123 after the first client has sent these 2 messages, the server creates a game instead of saying that it already exists, and in all cases the server returns the correct gameID.
public class Lobby : WebSocketBehavior
{
public Dictionary<string, Game> GameDict = new Dictionary<string, Game>();
protected override void OnOpen()
{
Console.WriteLine("New Connection");
Sessions.SendTo("Welcome To NDS", ID.ToString());
}
protected override void OnMessage(MessageEventArgs e)
{
Console.WriteLine(ID);
Sessions.SendTo("reΓ§u 5 sur 5", ID.ToString());
Console.WriteLine($"{e.Data}");
if (e.Data.StartsWith("ID"))
{
Console.WriteLine("Player searching Γ game...");
int Index1 = e.Data.IndexOf('D');
string GameID = e.Data.Substring(Index1 + 1, e.Data.Length - 2);
Console.WriteLine(GameID);
if (GameDict.ContainsKey(GameID))
{
Console.WriteLine("the game already exist");
}
else
{
GameDict[GameID] = new Game();
Console.WriteLine("the game has been created");
Console.WriteLine(GameDict[GameID]);
}
}
}
}
How can i do that
Your Dictionary needs to be static so it is shared by all players.
Instead of just checking if the Game exists you need to check if it exists and is not owned by this player
In fact your Dictionary should probably be a ConcurrentDictionary anyway
Thanks for your help, I didn't understand everything, but I'll look into it!
how do I pause everything except some scripts and sounds to make it look like game crashed?
public void AddToInventory(Interactable currentInteractable)
{
whatSlotToEquip = FindNextEmptySlot();
itemToAdd = Instantiate(Resources.Load<GameObject>(currentInteractable), whatSlotToEquip.transform.position, whatSlotToEquip.transform.rotation);
itemToAdd.transform.SetParent(whatSlotToEquip.transform);
itemList.Add(currentInteractable);
}
Argument 1: cannot convert from 'Interactable' to 'string'
I dont get how to fix this i looked at the error forms etc
public Interactable currentInteractable;
void Update()
{
CheckInteraction();
if (Input.GetKeyDown(KeyCode.F) && currentInteractable != null)
{
if(!OpenInventory.Instance.CheckIfFull())
{
OpenInventory.Instance.AddToInventory(currentInteractable);
currentInteractable.Interact();
}
else
{
Debug.Log("inv is fulll");
}
}
}
the Interactable script
which string variable does a GameObject have that might be useful in a Load ?
exactly what I said. Go and have a look at the GameObject documentation
.load requires a string path, and you pass a instance of your class to it
you'll have to be more specific at "some scripts". Setting the time scale to 0 might suffice here
Are you able to send the right one
tbh If you cannot even search the documentation yourself you don't deserve to be helped
https://docs.unity3d.com/ScriptReference/GameObject.html
I had the right one. Just wanted to make sure
Actually, my bad. this is the one you want
https://docs.unity3d.com/ScriptReference/Component.html
or even this one
https://docs.unity3d.com/ScriptReference/Object.html
https://docs.unity3d.com/ScriptReference/Resources.Load.html
this ones too huh
not yet, no
Why not? if the GameObject is not useful in a load do i even need load at all
for Resources.Load you need a string, as you know, what I am trying to teach you is how to get that string
So i need to get the GameObject as a string
you need to get your object (currentInteractable) as a string and the Object documentation tells you exactly how
.ToString()
I don't know why you're not just using basic references https://unity.huh.how/references/references-to-prefabs
exactly. and ToString() return name so .name also works
so when will unity finaly do smth that unreal does make our lifes easier ?
liek motion matching .. for example ? to get rid of that ridicolous state machines ? π
unity devs should take a look at latest news from unreal 5.4 thats jsut fck insane ..
They had a motion matching solution before Unreal, it was just sidelined while they developed DOTS.
π€·
I presume they'll resume it when they remake the animation system
well they should
animation system is pretty mutch outdated
automatic rig creation also a sweet thing wiht premade limbs n shit
Sadly we'll have to wait for Unity 7 before anything happens, but I imagine it'll be a large refresh with the .NET upgrade. A chance to change the engine properly
Kinematica is pretty much dead, the original devs are no longer at unity and unity has no interest in maintaining it or further developing it
I realise this whole convo is irrelevant to this channel
It is π
So i did
Instantiate(Resources.Load(GameObject.ToString(currentInteractable))
And then i get
No overload for method 'ToString' takes 1 argumentsCS1501
I didnt see it on the Docs so i tried to search and i saw the '?' for null
but when i tried
Instantiate(Resources.Load(GameObject?.ToString(currentInteractable) ??)
It still didnt work
So idk if i didnt it right or what
Everything you're writing is complete nonsense
probably is ngl, im new
Then follow a tutorial, and post in #π»βcode-beginner
