#archived-code-general
1 messages ยท Page 6 of 1
@cosmic rain
public bool hasTogged;
public ToggleRagdoll mainRoot;
// Start is called before the first frame update
void Start()
{
mainRoot = GetComponentInParent<ToggleRagdoll>();
}
public void ActivateToggleScript(bool ragdollOff)
{
mainRoot.ToggleRag(ragdollOff);
hasTogged = ragdollOff;
}
Added this script to every body part and now the bullets only have to get component once from the hit body part. The performance is now amazing!
it still shows up on games that I play?
i vaguely remember something about a command line arguement though
the games you play could be built on old unity versions
Any documents on how to make a settings menu then?
do not think so sorry, i personally have a script with references to a canvas group and components inside that group
with an apply button that reads the values from sliders and whatnot and saves it to disk / applies settings
Here I'm trying to Unsubscribe and Subscribe models from the "Flashlightchange" event depending if the "Current Model" or "Previous Model" Exists.
"flashlightchanged" is a boolean. Any help on how I can fix this?
I get error code: CS:0019
essentially that bit of code inside the curly brackets is called every time the flashlight change event is called
this all makes no sense.
This is wrong
oh sorry!
And will not work properly
The Flashlightchanged method is right there. It's not a boolean
yes i made a mistake
If Flashlightchange is a boolean, then this logic makes no sense at all
It would need to be a delegate for this to make any sense, not a bool
why are you assigning to a method with +=?
I was following a netcode tutorial and that tutorial uses Color instead of a boolean.
I dont really know what Im doing so I just followed along.
Follow along closer then! Presumably that's an event, not a boolean
Make sure you declared it properly
No?
Just... If you're copying a tutorial make sure you didn't screw up
Seems like you screwed something up
Possibly in the FlashlightSyncModel script
Or FlashlightChanged
I'm not trying to 1:1 copy the tutorial
the tutorial syncs Changing color through the network
while I want to change a boolean from true to false to enable a gameobject.
actually posting the error might help instead of the error code
which nobody can interpret
If you're not 1:1 copying it's going to be difficult if you don't understand the concepts behind the code. Have you worked with delegates/events before?
I've worked with events a few times
Yeah the tutorial was dealing with event subscriptions here and you still have that syntax
If you just want to change a bool, just change the bool
You know, with the = operator
You can't add a function to a bool
Yeah that makes more sense
Im going to run the game and see if the Server can see what the client does
Ill be back
what types are allowed for the object type argument in editorguilayout.objectfield()? it seems way harder than it should be to find it in the docs.
So, I'm trying to reduce my player helath using Lerp everytime it takes damage from the enemy. But the health is just snapping everytime the player takes damage. Any solution?
Can someone help enlighten me on why using composition through unity components, rather than in code (strategy pattern) is beneficial? Other than the obvious hassle of cross references between components, it also seems easier to ensure that all the correct "components" are present in an object through code, than through components? I have been looking for articles on it, but i havn't been able to find anything
Heyy, could someone please explain this error to me. Why property is deprecated?
Because it's not in use, deprecated means it's been replaced
Use what it says it's been replaced with
You can see an example here https://docs.unity3d.com/ScriptReference/ParticleSystem.MainModule-startColor.html
sorry, one last question. I understand the example, tysm, but this one line var main = ps.main; what does .main do?
WTH, what does it mean? ;/
Symbol bug in editor?
What is ps
Gets the main module from the particle system variable
oh, so unlike box collider or audio source, particle system has many component branches, and .main accesses all of them?
It has modules that contain the parameters, yeah
OK ty so so much
What are these things called again?
using directives
what am i doing wrong here?
Don't include the file extension in the path
You specifically left out the line number in the picture
NullReferenceException means "You try to invoke a method on a reference that is null"
Guess what the method is
i didn't notice. it's the line with kernel = shader.FindKernel
Correct, shader is null ๐
how do i make it not null?
ok. i'll try that.
You google Resources.Load.
You find: https://docs.unity3d.com/ScriptReference/Resources.Load.html
It quotes "This method returns the asset at path if it can be found, otherwise it returns null."
It also quotes "Note that the path is case insensitive and must not contain a file extension."
Debugging is a good skill to have
Solution: "must not contain a file extension"
Or it doesn't exist in general of course
I have a tilemap and I'm wondering if there is a way to fit it in the whole cinemamachine screen?
I have 16:9 res selected, but when I walk to a direction it stills scrolls a little bit
Hello, friends.
I'm assigning a scriptableobject on Awake and then calling it every Update:
void Awake()
{
this.object = ScriptableObject.Instantiate(this.soType1);
}
void Update()
{
this.object.Tick(this);
}```
Then on a trigger collision, I change the reference of `this.object` to another scriptable object that I instantiate:
```cs
private void OnTriggerEnter(Collider collider)
{
this.object = ScriptableObject.Instantiate(this.soType2);
}```
Weirdly enough, both `Tick()` methods are being called on `Update` as if `this.object` is keeping the reference for the two instances. Anyone knows what can be happening?
I need some brainstorming to solve a problem, In this senario I am generating a building, What you are looking at are the second floor. It does have the bouneris of the first floor. In this senarion i can chop of most of the green parts that reperessetns corridors to make it look a bit better and that there are not ofen you see a corridor that is so big. How whould I do it, It is based on a 2d array
Use syntax highlighting #854851968446365696
I seem to be having an issue using IPointerClickHandler.
My UI element that contains the script that is using IPointerClickHandler is set active and moved roughly to where the mouse cursor is.
If I then left-click on this UI element (without moving the mouse at all), OnPointerClick will not fire.
Only when my mouse has moved at all before clicking will OnPointerClick fire.
Any thoughts?
sorry i just saw your response on this, what I mean by better is if it is less resource intensive, but I also want to know if this is actually how it is mostly done or if this is a weird thing to do inheritance instead of multiple scripts in the same gameobject
what
public void TheGame()
{
position = Position1;
if (player1Culture =="Japanese")
{
JapaneseFoodInventory.SetActive(true);
while (!condition)
{
if(!JapaneseFoodInventory.activeSelf)
{
condition=true;
}
}
condition=false;
}else if (player1Culture =="British")
{
BritishFoodInventory.SetActive(true);
while (!condition)
{
if(!BritishFoodInventory.activeSelf)
{
condition=true;
}
}
condition=false;
}else if (player1Culture =="American")
{
AmericanFoodInventory.SetActive(true);
while (!condition)
{
if(!AmericanFoodInventory.activeSelf)
{
condition=true;
}
}
condition=false;
}
Displaytext.text = "Player has chosen an item";
}
}
Pls help
nice code
So I have this while loop
please do code blocks
Ok sorry
like this
```cs
(your code here)```
you can just copy paste the thing i sent and copy paste your code in lol
ok thats also legit
I am new to this
ok
Are u talking about the repetition?
instead of using multiple functions for each food or whatever that is
yes
you can just make one function
and pass it the argument
let me just give you an example
instead of this
void PlaceThing() {
Instantiate(thing);
}
void PlaceSomethingElse() {
Instantiate(somethingElse);
}```
you can do this
```cs
void Place(Thing theThing) {
Instantiate(theThing);
}```
just make a class for all the foods
Wait but I want it to to be functions for different buttons
just add the links with code
loop through the buttons
then link the Place function
to the onClick
and for each button you can just pass the function parameter depending on the button
if you have like a lot of buttons in sort like a list
you can also just add the buttons through code instead of adding them manually
Alg, fair enough.
Unfortunately I don't have enough experience to give a proper answer
but the problem I wanted to ask about is that
I have some while loops at like around line 290
and when I run the game
the game freezes
because of them
What can I do to fix that?
ooh wait i think this happened to me
i had a similar problem
but it may just work!!
i just remembered lol sorry
i believe you can reset the component of the element
just set enabled to false and then true
i think i did that and it worked
my problem wasn't that it wasn't clickable but instead it was not detecting the mouse hover
but my problem was because i had the timescale set to 0
Very interesting, thanks! I shall give it a try
and for some reason something about the collider of the element didnt work
but this was because i was using a boxcollider for the element
this was because it was on a 3d canvas in world space
so it could not use the mouse for it so i had to make my own raycasting in 3d to be able to click the button in 3d space
and what i did was disable and enable the collider again
and for some reason that worked so i kept doing that when setting the timescale to 0
so a solution like that may work for your case
yes thats also bad
you can't have a while loop like that
let me just check your code
i cant even understand what your code does
honestly i would just rewrite all that
๐ญ it's that shit. lmao
so i will briefly point out the things i would do
starting from the top, thats a lot of GameObject fields
ok thx
i would instead make a list
after that you have like 30 vector3 fields
thats also a lot of fields
instead of copypasting 234958023450892590 times
you can just make a list
thats what lists are for
after that, you also have some patterns here
I tried but my limited knowledge didn't come in handy
you should make a class for that and put the values there instead and just reference the class
after that, you have the 389457345 methods which do the exact same thing
expand your cranium. it's probably worth it
you can just make one method, and pass the argument to it
If your game freezes, it's almost definitely related to the while loops
and after that you have the infinite while loop
which is not good
i dont think you need a while loop for that
How can i replace it
delete it
What can I replace it with
nothing
or an if statement
i would just delete it and write it again
im talking about the while loops
not the whole thing
I have a day to submit my game
what
oh
ohhh boy
I learnt unity from scratch in the past 6 days
and you lost all that time copypasting??
thats cool
but you should have learnt C# first
no no. This is not my entire code
I have other stuff too lmao
no i know but
I made 50 3d models for the game
hey ist there a help cahnnel for problems with unity?
woah
what type of problems
code problems?
or just unity problems
No no Code problems, unity problems
oh okay
maybe #๐ปโunity-talk but i dunno
I just took a small unity course. Quickly finished it and got to coding
so it doesent matter if i ask in this channel here?
cool
just tell us what your problem is
or me
nice
me too actually
its too fun
okay, i want to open my Movementscript in unity but it is not opening, i am new at unity
i thought visusal studius gonna be installed if i install unity
yes it does i think by default
but you need to check if it is set in the external tools thing
I will finish the game rn. I will try to get an extension for my submission and shorten the code l8r
good luck
where can i find this?
thx
.
trueee
yes like that
file, preferences, external tools
on the top left menu
there's file
in file is no preferences
wait what
Preferences*
there ist just new project ...
here we go
I always confuse Project Settings with Preferences
what do you have the external script edit tool set to?
okay ia m on preferences
haha and now? xD
i just told you
.
External script editor?
open by file ...?
i literally asked you ๐ญ
no
send screenshot
visual studio should appear there
in the list
give me a second
ok
So I found this way on the internet to do it. Do I just put a comma after the first vector and the 23 other vectors I have?
yes
but please leave a line break after the comma(s)
Oh so that they all come in different lines?
wait hold on, how can you Remove() a new Vector3 from the list?
openai is a bit crack ig
I guess it will match if theres already one in there haha
I'll try it now, curious
ooh right because vector3 is not a primitive you cant have the list automatically remove the duplicates right?
XD
oh wait thats not the point
nevermind
thats not what you would use the list for tho
or how you would use it*
My XD wasnt in response to u Bruno, sorry the timing was unfortunate haha
BrunoRM
yes i know
My bad it remove the first instance matching it seems :p so new vector3 should work I think.
i love it
so there is just vs_community_ac58de352fa04
NO!
well that should be it
ok thanks for the feedback i appreciate it a lot
but its already choosen
then you should be able to
try opening a script
okay
or create a new C# script and double click it
Profiler is so confusing
yes
indeed
i never understood how to use it correctly
its just unity stuff
i want to debug my scripts but instead all i see is unity thing
YES RIGHT
trying new ways etc
OMG
Noo : ( its still not working ....
noooooooo
ok try this
open the visual installer
or whatever is called
check if your visual studio installation appears there
if you dont have the installer just search it and download it and open it
XDDDDDDDDD
LMAOOOOOO
why did you delete it!! its so fun!!
its not the correct channel tho
๐
might get banned
grammar mistake
was something wrongly written!?!?
i didnt notice lol
i deleted it because i thought it worked not because i have the wrong version. but ill donwonload it now again
lol
you thought it worked not
i see
what?
its "did not work" instead of "worked not"
I am fuckin german we dont have teachers
yes i know
so dont judge me
just pointing that out
oh you re so kind < 3
thanks!!!
soo now its installed
second
no i have a new file at the extrenal script aditor
Microsoft Visual studios 2022
i guess thats a good sign
but cant open it either
and unity is frozen like ice
try opening the whole solution in visual studio
uhm how? hehe
what is execution order for them? Init (Inject), OnEnable, Awake,Start?
In editor, I see first, call Init, then OnEnable but I think I saw OnEnable is executed first then Init in runtime. Is it random?
For start, it is OK and always runs after
When I get close to a collision enabled object, this thing happens https://gyazo.com/352b4479c441a308665640d2d317e0ae, this is my code: https://paste.mod.gg/tbxcavfkzozb/0, anyone got a clue why this is happening and how to fix it? (attached pics of the collision boxes)
A tool for sharing your source code with the world!
awake is first, and start is last
i dunno the rest
How can I wait for a function to end before continuing one
you can use Invoke
or a coroutine
ok thx I will check them out
@earnest gazelle https://docs.unity3d.com/Manual/ExecutionOrder.html
zenject
ok
OK, because zenject procedure runs in Awake (SceneContext), so calling Init methods before or after OnEnable is not certain
@earnest gazelle ah, surprising if they don't have it documented
I did not find it
public void Awake()
{
#if ZEN_INTERNAL_PROFILING
ProfileTimers.ResetAll();
using (ProfileTimers.CreateTimedBlock("Other"))
#endif
{
Initialize();
}
}
SceneContext
if OnEnable is Unity one and not Zenject specific then it should be executed after Awake, so unless Zenject has some lazy init going on which might be executed outside Awake then it should be safe
I sometimes wish Unity had multiple Awakes, would make things easier for handling dependencies of pooled objects
OnEnable runs after Awake inside that mono
Awake1,OnEnable1,, Awake2,OnEnable2...
So Awake SceneContext can run before or after OnEnable some monos
Awake1,OnEnable1, Awake2, OnEnable2, Awake (SceneContext), Awake3, OnEnable3...
Ok, I haven't used Zenject, so I'm not really sure what exactly is the problem here or what you are aiming for. SceneContext Awake running before OnEnable of anything else?
If you don't know the execution order, you can easily get null reference error
can't you just solve this by forcing SceneContext to run first?
Unless you need things to run between Awake and OnEnable of specific objects this should be solvable with Script Execution Order
Before, my code added listeners and removed them in Start, OnDestroy. It was completely OK
Now, I saw null reference errors after 3 month in the recent build because my teammate has changed it to OnEnable,OnDisable.
in Init zenject it assigns an instance, then add/remove listeners in OnEnable,OnDisbale
[Inject]
private void Init(TypeA instance){
_instance = instance;
}
private void OnEnable(){
_instance.AddListener(...);
}
private void OnDisable(){
_instance.RemoveListener(...);
}
When you don't know and change codes you have not written ๐ญ and also do not know about zenject. It causes a sh.. bug exists in release
Probably yes, force execution order in setting but it is another scenario and I do not like it.
For each scnee, add scene context to that list,..
yeah hmm, SceneContext is something that executes init? if it has references to everything already then just forcing it to execute first
well, I'd say whatever kind of dependency management system you are using you'll likely need to manipulate execution order list
execution order is project specific, not scene specific
yes,
if we are talking about unity's build in Script Execution Order settings
yes, I mean if I decide to add them manually, I should add all scene contexts for all scenes and care if a new scene has been added, again add its scene context to the list
Generally, I try to choose another solution if I can like start/onDestroy instead of OnEnable/OnDisable when using Injection as well
@pine spire thanks
I'm having some trouble with Vector3.Reflect
instead of reflecting on the normal its reflecting perpendicular at it
nvm I was passing the hitting point not its direction
Upon further investigation, when trying this the other way, like tr2.position = tr1.position, it consistently works all the time (or at least, I didn't get it to fail). I didn't find any other reference to that gameobject in the game, and the Interpolation script was disabled/deleted, yet it still doesn't want to set position. What can be wrong here?
Does tr1 have a CharacterController on it
Or Animator?
no, aside from mesh stuff, rigidbody and trail renderer, it only has a script for changing trail color, interpolation script (which can be deleted for no effect) and NetworkObject component
I mean, there's basically two possibilities here:
- you're confused about which object you're moving or where you are moving it.
- some other component or other code in that Same script is moving it back to where it was
How are you referencing tr1?
Is it actually an object in the scene?
Or is it maybe a prefab or something
Well, is there a way to check which script is affecting the position? Maybe there's something I'm not aware of, because it's definitely not the Interpolation script
tr1 and tr2 are both set in the inspector, they are objects
From where though
What exactly did you drag in
the objects in hierarchy to respective slots
i'll just add, that it sometimes does work
Again setting transform.position works. So something else is affecting it then
NetworkObject seems really likely to be part of the problem
Anyway I gtg start work
just checked the NetworkObject script, it doesn't modify transform.position anywhere. And then, it doesn't explain why it sometimes does actually work, and why other objects, which also have NetworkObject component can teleport without any issue.
Just wanna clarify my understanding on this method
a ray is an invisible line from a specific point of origin towards a specific direction
yes it has a origin point and a directional vector
screenpoint is a point that is halfed the screen's width & length?
so the screen point for this screen size is (512, 384)
no screen point is not halfed
its just the pixel coord on the screen
bottom left is (0, 0) top right is (Screen.width - 1, Screen.height - 1)
screenpoint can represent any point on the screen?
yes
also mouse position is in screenspace
so can be directly used as a screen point
ViewportPoint version is also useful
same idea but buttom left is (0f, 0f) and top right is (1f, 1f)
so this method of ScreenPointToRay(); would cast a point from the screen towards specific direction? Kinda like shooting?
can anyone tell me why this saving code doesn't work, i've debugged everything and it just seems like some things just aren't happening when they're supposed to be
a powerful website for storing and sharing text and code snippets. completely free and open source.
yep, give it a point on the screen, and it return a ray facing down the cameras direction from that point
define "doesn't work"
I heard of this, I'll give it a read later thanks
you can use it in a raycast directly if you wanted to ray cast from the screen to click on a object
I've made a dummy gameobject, and tried setting its position - it works, and despite 10 tries i didn't get it to fail, so i assume it's consistent. But when I set the reference back to the original gameobject, it doesn't work. I've tried copying it (to effectively make a new gameobject), still doesn't work.
gotcha, thanks for the quick & the detailed breakdown
also you should not use BinaryFormatter @normal arch
BinaryFormatter is insecure and can't be made secure. For more information, see the BinaryFormatter security guide.
The BinaryFormatter type is dangerous and is not recommended for data processing. Applications should stop using BinaryFormatter as soon as possible, even if they believe the data they're processing to be trustworthy. BinaryFormatter is insecure and can't be made secure.
yes heavily recommend not using the binary formatter
use something like json for quick and dirty stuff, or design your own binary format if you really want to use binary
๐ Quick question, in the unity docs it says I can use IgnoreLayerCollision to turn off collisions between two layers, how do I turn them back on after?
just do it again and set it to false..
@short ridge
That's for 2 colliders, not for layers no?
the layer one has the same bool arg
they work the samme
its just a optional arg, if you do not provide a 3rd arg it assumes its true
public static void IgnoreLayerCollision(int layer1, int layer2, bool ignore = true);
๐ hi people, you know that feature on mobile devices where to have a element in a list an you can delete that by swiping to the left or right? thats what im currently replicating and its working fine but one problem occured. im using the IDragHandler - On Drag method for it but when i start dragging im not able to scroll inside a content size fitter scroll view which is not the typical mobile behaviour for apps. maybe someone has a clue?
it doesn't clear the inventory nor add the items saved
what is the function to make all players leave room and lobby in photon?
Is it possible that turning on rigidbody interpolation for a gameobject causes problems with setting position? Did some testing, and I think this might be the issue
cant test right now, but when done in your OnDrag try calling Reset on the event data
also why are you trying to mimic phone style UI in unity. unless you need features of the game engine like 3d rendering or physics i would opt for a different tool
@quaint rock hey thanks for replying. i tried eventdata.reset() but didnt change anything
hmm if that did not work, think best you could do is in your drag event, manipulate the outer scroll rect as well as doing your other logic
scroll rects also implement the various interfaces for drag events
for(int i = 12; i > 0; i--)
{
var r = Physics2D.Raycast(transform.position, new Vector2(i*5, i * 5),100,SightObjects);
}
This should give me a rough cone of raycasts right?
@quaint rock okay.. hm im thinking how i could use that in my case
not sure without trying, but could use gizmos to make it easier to see what is going on
https://docs.unity3d.com/ScriptReference/Gizmos.DrawLine.html
which handlers are you implementing ?
just OnDrag, or also OnBeginDrag and OnEndDrag?
im using IBeginDragHandler, IEndDragHandler,IDragHandler and im just implementing idraghandler because otherwise begin and end would be triggering. in begin i set dragging bool true and in end i set it to false rest is in update
yeah so a scroll rect has the methods from all 3 of those, so assuming you can at the end of your handlers just call the same methods on the scroll rect you want to scroll
would not*
Hey, I have a problem with one of my codes. I want to do a specific animation at a combination between my mouse and some Keys. Somehow the animation works at OnMouseOver at top(w) but not at top(s). Like I get this error when I try to change the speed at top(s):
Animator.speed can only be negative when Animator recorder is enabled. Animator.recorderMode != AnimatorRecorderMode.Offline
UnityEngine.StackTraceUtility:ExtractStackTrace ()
mouseTop:OnMouseOver () (at Assets/scrips/mouseTop.cs:50)
UnityEngine.SendMouseEvents:DoSendMouseEvents (int)
(ps: it should be enabled)
And also If somebody has an Idea, how to stop the animation, let me know. I tried something at the end of the Code which didn't work out.
The Code:
https://hatebin.com/tyegcgqioq
I uploaded it like its said in -read-me.
could you suggest an alternative and how to use it
Bump. Anyone at all that has an idea? :)
use JSON like suggested, you can do BinaryWriter
Hopefully this is an easy question. But I have a dropdown that works in the inspector, but when I build the game, it's completely blank. Not sure if it makes a difference, but the dropdown is to change resolution in the game
show code
why would something in an inspector be in a built game?
even more so, how?
Let me know if I need to clean it up, it's a bit wild lol
https://gdl.space/hojiqiwifa.cs
Sorry, I'm stupid lol. I meant to say when I hit play in Unity and play it there. Not the inspector
best guess your anchors are wrong for your TMP_Dropdown
I would start by seeing if the list is truly empty. use OnGui and debug some values on the built
Also you might want to look at the documentation for the switch statement
you can also Debug.Log and look in the logfile in the build make sure ur getting what ur expected
you can build the game with the Development box checked, and see the exception it throws
that is most likely what is happening.
this script is really complex for what it does
unity has a built in graphics settings popup you can turn on for the start of the game
are you sure you don't want to use that for now?
For some reason I didn't know this existed lol. Checking this now
@quaint rock got it working with ipointer handlers enter exit and click ! ๐
Thanks so much! That did it.
Looks like this line resolutionDropdown.value = shortResolutionList[i]; was messing it up since I was calling the output from a list, I just changed it to resolutionDropdown.value = i; and that resolved it ๐ญ
How do I use Lerp for doing continuous damage?
https://paste.ofcode.org/FWiiMjviPRQXEs7Mg6Rgfv
This code works fine for single damages, but when doing continous damage, this happens:
is there a way or an alternative to the sprite mask for unity 5.6 ?
whats continuous damage
i would use Mathf.MoveTowards in update to reduce the display health when the display health value is not the current health value
you could set the per second delta / move speed based on the distance between current and the target
Im coming from Gamemaker 2 to Unity and don't understand how to link parameters and functions to a prefab itself. I know Java/C# so I have created a class but I don't understand how to link the class to the actual prefab. With Gamemaker I would have done a with(instantiate()){ whatever i needed to set}But from what i see, its like its not possible to have a unity gameobject carry these parameters.
Tldr; I want to instantiate a object with parameters and don't know how.
public MyScript thePrefab; // drag and drop the prefab here in the inspector
void SpawnAThing() {
MyScript newInstance = Instantiate(thePrefab);
newInstance.Whatever = whatever;
}```
^ this is assuming your prefab has a script attached to it called MyScript
with variables you want to set or methods you want to call
but what is the .Whatever? If i had something create a prefab. How does the prefab have a parameter in the first place
It's a field on the script
for example:
public class MyScript : MonoBehaviour {
public int Health;
}```
then you can do newInstance.Health = 5; for example
but how is that class script linked to the prefab?
it is attached to it
prefabs are just GameObjects
you attach scripts to GameObjects
So just attaching a class script to a game object will let you set the parameters when instantiated?
weird way of wording it but, if you use the technique I showed above, yes
"when instantiated" is kinda irrelevant here, you can interact with the script at any time
in this case we happen to be doing it right after instantiation
but each prefab will have its own parameters right?
The prefab doesn't have parameters
It has scripts attached to it
the scripts can have fields and functions on them
and you can interact with those functions and fields
functions can have parameters
So im changing the script attached to the prefab on creation?
and each prefab will have its own copy of that class script with its own parameters?
yes
though again they're fields and functions, not parameters
also when you say "each prefab" it's important to distinguish what you mean
a prefab is the premade object that sits in the project folder
right
when you Instantiate a prefab you create an instance of the prefab
which is a totally new copy object that is now in the scene
you can interact with that particular instance, which is what my code above is doing
gotcha, yah thats what i meant
I just like to be precise with language because I don't want to cause any confusion
Ok thank you so much! Different work flow than Gamemaker but I guess that makes sense. Im used to the instance itself having a predefined script that embodies everything that object is
Yeah Unity uses a component model
the GameObject itself is basically just an empty shell
all the data etc is on Components attached to the GameObject
I do like that though, very minimalistic
I know Unreal also uses the model where you override Actor to create specific types of actors, Unity is a bit different than other engines I guess
Never used GameMaker myself
honestly I loved Gamemaker, Its super stable and just makes so much sense when you get the basics. Its very easy to master, but I switched to unity because I got sick of writing my own packet definition scripts and writing my own server libraries for multiplayer games
what feature of GameMaker in Unity you wanna know, I used to use Game Maker till version 8
also, it sounds dumb, but with Gamemaker, mobile apps have a small black bar at the camera line that you just can't get rid of, so I am using unity for this mobile app project
PraetorBlue was helping understand how the C# classes actually link to the unity prefab
It may sound kinda bland but I think it would actually help to read the GameObjects section of the Unity manual. It may help clear up some confusion too:
https://docs.unity3d.com/Manual/GameObjects.html
https://docs.unity3d.com/Manual/Components.html
Not a long read
Thanks but I have already read those and really do understand GameObjects, Iv created about 3 projects in Unity before this but just have never needed to have a C# class for data organization be embodied by a prefab. I definitely prefer Unity's component system over Unreal Engine's actors. Gamemaker was just 1 step more simplistic in that it was just a object with a script and thats where you did everything.
is there a way to hide gameobject for only certain camera but not others?
So I have the oppurtunity to upgrade my unity machine with a 7900xtx, or like 200+ cpu cores on a quad socket xeon. What would benefit production more a highe end gpu or more cpus. I already have a 6800xt.
you can exclude specific layers from being rendered by a camera, so you would put that object onto a layer that only the specific camera you want sees
neither would make any difference
ok I'll try this ^^
it worked tysm ^^
void Update()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector2 movementDirection = new Vector2(moveHorizontal* speed, moveVertical* speed);
movementDirection.Normalize();
if(movementDirection != Vector2.zero)
{
Quaternion toRotation = Quaternion.LookRotation(Vector3.left, movementDirection);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
}
else if(movementDirection != Vector2.zero)
{
Quaternion toRotation = Quaternion.LookRotation(Vector3.right, movementDirection);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
}
}
how can I rotate my character in the left and in the right on the y axis
bc idk why when I press A it goes only like 90 degrees
try using Quaternion.Rotate
Stop crosspostibg
yeah maybe try both
is there an appropriate place to discuss theory over Chat GBT within this discord. I know you guys know your stuff and I'm looking to pick someone's brain.
And you don't want y axis rotation in a 2d game
As you've been told, no
I was told that channel
then what do I want?
thank you
To continue your discussion in #๐ปโcode-beginner
ok
Guess i don't understand...
You defined your prefab as GameObject
As per my example you should declare it as Bubble
Isn't Bubble a child of GameObject though?
Note that you'll need to re drag the prefab into the slot when you change the type
Or you'll get an error at runtime
Is AssetDatabase for editor use only? Is any of it useful in a build?
hmm i guess no because it's in the UnityEditor namespace
I dont know if its bad or good.
Editor only yes
Look into Resources.Load or Addressables
yo, this worked thanks
Hello. I have a slightly complicated question. I have looked online for a while but I can't find anything about it.
In essence, I want to find how AnimCurve.EaseInOut is calculated. This is all I could find in the documentation: https://docs.unity3d.com/ScriptReference/AnimationCurve.EaseInOut.html but it doesn't specify how it's calculated. I know its some type of nonlinear interpolation, but to what degree?
Check out the column on this page for "easeInOut". https://easings.net/ It will be one of those. My guess would be the sine, but use your best judgement.
woah how'd you find that
yo, anybody knows why
SceneView.currentDrawingSceneView.camera.transform.position
might be returning null inside the unity editor?
I am just trying to get the view camera position
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
[RequireComponent(typeof(LensFlareComponentSRP))]
[ExecuteAlways]
public class LensFlareConstantScale : MonoBehaviour
{
LensFlareComponentSRP flare;
public float size = 1;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (flare == null) flare = GetComponent<LensFlareComponentSRP>();
var cameraPos = Camera.main.transform.position;
#if UNITY_EDITOR
cameraPos = UnityEditor.SceneView.currentDrawingSceneView.camera.transform.position;
#endif
float newScale = Vector3.Distance(transform.position, cameraPos);
flare.scale = newScale*size;
Debug.Log(newScale);
}
}
I think that's only not null at very specific times
sad
I found no resources online for getting the camera position, if you could throw me a bone it would help lol
testing
that did it
thanks
I am mindboggled that googling for "editor camera position unity" gimes me 3 pages of results
I think this is a very sensible question LOL
My google search was unity get scene camera position
seemed to get reasonable results
question if i have a class that has using System; is the class still serializable?
using directives have no bearing on the code itself
They just let you use short names for classes
It lets you write Serializable instead of the full name System.Serializable that's all
Got it
I just google something like "unity animationcurve cs" and check their reference source out
unitycsreference is what I Google instinctively to find their GitHub repo
TIL if I press t in github repo I can search by filename
Yep!
Sorry for the late response, to get this to work, just add an empty GameObject with this script attached, and then put a PhysicsBody tag on all the GameObjects you want to be in the prediction simulation! Note I'm using PhysicsEngineUpdate() as I'm using my own physics so to call an update from my physics engine I use this function!
I forgot about you already tbh
Does PhysicsEngineUpdate get called 50 times a frame?
private void FixedUpdate()
{
PhysicsEngineUpdate();
}
public void PhysicsEngineUpdate(string tagFilter = null)
{
if(tagFilter != null)
_gravity.SimulateGravity(TagFilter(_PhysicsBodies, tagFilter));
else
_gravity.SimulateGravity(_PhysicsBodies);
}
That's basically what the physics engine does
Just allows me to manually call physics updates when needed for the prediction engine
Thanks
Ray ray = currentCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out info, 100, LayerMask.GetMask("Tile")))```
Even when I keep my mouse completely still over an object, it sometimes doesn't count it as a hit.
idk why my character only rotates once and then no more
#854851968446365696 for how to share code
wdym its with pastebin
lol you're not supposed to download the text file from pastebin and share the file, you're supposed to share the link
also pastebin sucks, use a better site like one of the ones linked in #854851968446365696
you realize you are starting an instance of that coroutine every single frame, right? so if you are running at 60 frames per second, by the end of a single second you'll have 60 instances of that coroutine running
not realizing much atm I am working on this shitty game for like 6 hours without breaks and did not progress much
then maybe take a break and come back to it with a fresh perspective?
then you should rest up and start with a fresh mind
trust me when i say this will be easier for all of us if you take a break then come back to it with a fresh mind. i've already pointed out a pretty major issue with your code so after your break, address that then if you're still having trouble figuring it out ask here
I'm trying to set a dropdown's value to the current resolution at startup. I feel like this should be right, but for some reason it always sets it to my monitor's resolution instead of the game's displayed resolution
https://gdl.space/sikipaduwa.cpp
cuz you are clearing maybe
I actually had the same thought right after I posted that hahaha, but sadly that didn't help
would definitely help if you posted at least how the variables are used before and after this excerpt
Shoot sorry, let me get the whole script. It's kind of a mess rn since I've been trying to figure this out for 3 hours lol
I think there are some premade windows for such stuff
So ApplyChanges is empty, you know?
Yeah, but I'm not calling it yet, that'll be once the stuff that's commented out in ChangeResolution is active
You are using such a line to apply the changes fullscreenDropdown.value = 0;
Are you sure it does what you need?
Oh, your window is made with unity
Ah yeah, that one is just to get the fullscreenmode in the beginning and set that dropdown to the right one. The one that's giving me trouble right now is: resolutionDropdown.
So you check your results simply by checking what the dropdown displays?
Perhaps swap these 2 lines?
resolutionDropdown.RefreshShownValue();
resolutionDropdown.SetValueWithoutNotify(currentResolutionIndex);```
Exactly, since I want the dropdown to set it's value to the current resolution. So I keep trying to build the game, change the resolution and open the dropdown to see if it's being set to the right one
.
Let me try thgat
Shoot, same thing. I changed it to 640x480 and then refreshed the menu, so it should show that as the resolution instead of 2560x1440
Why do you even use this !optionsList.Contains(option) condition if Start method gets launched only once?
I actually have it set to run again onEnable. That way when the new scene loads with a different menu, but the same script, it'll re-check the resolution
That way I can also keep troubleshooting it while playing it
Okay. Really stupid question, but the code channels in this server do not talk about the same code as in c#?
I want to make sure I absolutely am understanding right
Perhaps place a debug here to see if the condition is satisfied?
if (defaultUnityResolutions[i].width == Screen.width && defaultUnityResolutions[i].height == Screen.height)
{
currentResolutionIndex = shortResolutionList.Count - 1;
}```
C# is the same everywhere
But people here are way more familiar with everything related to Unity
Yes but the code spoke about in these code channels isn't c# or is it?
I actually just tried that
https://gdl.space/abubeluxip.bash
I see that debug showing up twice though, so I'm gonna try to add a clear to the beginning of Start()
It is C#
Okay. I got confused as when I asked about c# I was directed to a c# server previously that's all.
Here? Well, you shouldn't have been
Well a different channel but they distinctly said the c# server.
Maybe for general c# as opposed to unity specific?
Here we talk about Unity related code questions not general C# questions
Unity code is written in C# yes
Probably you shouldn't ask data bases related questions here yeah
Ok so if I have a question about c# when using unity, I ask here. But other stuff elsewhere. I think I got it. Maybe
or c#10 functions xD
Hopefully I can figure out the difference before I ask lol. Thanks for the explanation. I appreciate it
You won't get punished or anything, just ask and you will get it after a few questions
Ok. ๐ At this time no further questions tho. X.x tysm
Then try to debug Screen.width there
How much is it?
I mean
In the last brackets we talked about
if (defaultUnityResolutions[i].width == Screen.width && defaultUnityResolutions[i].height == Screen.height)
{
currentResolutionIndex = shortResolutionList.Count - 1;
}```
These ones
This is the current resolution: 19 ,1920 x 1080 @ 59Hz
UnityEngine.Debug:Log (object)
Video_options:Start () (at Assets/Scripts/UI Scripts/Video_options.cs:72)
Video_options:OnEnable () (at Assets/Scripts/UI Scripts/Video_options.cs:124)
Changed vSync value to: 1
UnityEngine.Debug:Log (object)
Video_options:vSyncChange () (at Assets/Scripts/UI Scripts/Video_options.cs:147)
UnityEngine.Events.UnityEvent`1<int>:Invoke (int)
TMPro.TMP_Dropdown:SetValue (int,bool) (at Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_Dropdown.cs:431)
TMPro.TMP_Dropdown:set_value (int) (at Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_Dropdown.cs:406)
Video_options:Start () (at Assets/Scripts/UI Scripts/Video_options.cs:95)
Video_options:OnEnable () (at Assets/Scripts/UI Scripts/Video_options.cs:124)
Changed fullscreen mode: Windowed
UnityEngine.Debug:Log (object)
Video_options:FulllscreenChange () (at Assets/Scripts/UI Scripts/Video_options.cs:198)
UnityEngine.Events.UnityEvent`1<int>:Invoke (int)
TMPro.TMP_Dropdown:SetValue (int,bool) (at Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_Dropdown.cs:431)
TMPro.TMP_Dropdown:set_value (int) (at Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_Dropdown.cs:406)
Video_options:Start () (at Assets/Scripts/UI Scripts/Video_options.cs:111)
Video_options:OnEnable () (at Assets/Scripts/UI Scripts/Video_options.cs:124)
This is the current resolution: 22 ,1920 x 1080 @ 59Hz
UnityEngine.Debug:Log (object)
Video_options:Start () (at Assets/Scripts/UI Scripts/Video_options.cs:72)
I's what's logged?
So it seems to run once and finish under Start(), then run again
You have quite many debugs I see
I tried running that block for the resolution just under the OnEnable and that mostly fixed it, but now when I build the game the dropdown isn't populated lol
The other two in there are actually the ones at the end of the Start() script, so I would expect them after the OnEnable as well though, so I'm not sure why it's only running through that block more than once
Yeah ๐ญ
So 1 + 1 = 2
And twice is more than once
So why are you surprised the block is used twice
Oh sorry, I should've explained that better hahaha. I'm not surprised it ran twice, but I am surprised that it found the same resolution the second time, but as a different index number, when it basically should've run the Start() function twice
That ended up fixing it though, thanks so much for the quick responses and insane amount of help!
I think half of the time I must have looked like I was saying stupid things
But okay
LOL nah, you at least got my brain thinking and working towards the right solution
hey,
how bad is it to make a list of 2000 items of a custom class, (the custom class would be something like that)
public class BoxItem{
public int currentNumberOfItems;
public int maxNumberOfItems;
public string brandName;
public string itemType;
public bool option1;
public int option2;
public bool option3;
public int option4;
public bool option5;
}
on a relay server that also holds this "database"
and whenever a player asks to get an Item from the box, I need to look for a box with those filters( type: "TypeA", brand:"ThisBrand", op1:false, op2:3, op3:true, op4:3, op5:false) , I should loop through the whole list and find the boxItem that he wants knowing the following
1 - there might be up to 500-15000 people online at a time.
2 - I dont need to keep the database of the box after it's empty and gone
do I need a database for that or a simple list with a for..loop is enough ?
Sounds expensive
I read online 2 answers about this , some says 10000 is like nothing for server, others said "you are better off with a database" , so Im not sure.
but its not just a server its also a relay
Not sure about the specifics
But jobs+burst boost performance of monotonous tasks very much
Depends on your server's count of cores tho
Well, jobs don't really give extra performance with 1 core
But 1 core doesn't sound fine for 1000 players too
hmm, I would probably expand to 8 at least if 1000-10,000 ppl joined
but to start I just want to use 1core
But you of course can implement some optimisation techniques for your database
so you are suggesting a database instead of a list ?
For example keep track of lists of items with the same characteristics
And update the lists once a new box is spawned or a currently alive on is changed
So you will have like a separate collection for each variation of each parameter
It will boost performance quite a bit
Tho memory consumption will rise up
its ok if the player waited few seconds for this to update.
so multiple lists would be better than SQL ?
Not worked with SQL and not knowledgeable about its optimisations, but compared to filtering through all the boxes each time this approach is pretty fast
Depending on circumstances of cource
Do players modify that list as well or is it just read only
modify
You are better off with database
-
Reposting it here, apparently this doesn't fit the beginner channel.
-
I have my own state machine class that has a registry of state classes that implement an interface, and a registry of
state-statetransitions. I'd like to implement astate_type-statetransitions, but how could i? Specifications:
State is any class that implements a corresponding interface
State_type is any state that is marked as abstract
Transition contains a goal state and a condition
Transitions are performed by getting a list of transitions, corresponding for the current state and checking its conditions, swapping to a goal state if it returns true
- So an example would be abstract classes
Idle,MoveandCrouch, all of them are inherited from abstractGrounded. After i add a transition fromIdletoCrouch, it works only for these two. However if i add one fromGroundedtoIdle, it works for any of the mentioned states
Say we have class StringUsersTracker and class StringUsersTrackerService the latter of which is a singleton or you get a reference to in our box otherwise. Then you do stringUsersTrackerService.Subscribe(myString, this) which checks if there is a StringUsersTracker associated with the string, if there is one then connects your this to the tracker. If there isn't one then first creates then connects. And when you request stringUsersTrackerService.GetBox(typeName = "Gucci") it again checks if there is a tracker associated with it. If there is none, says no such boxes. If there is one, creates a short living list, adds all string users from the tracker to the list and returns the list.
If there are more requirements to the boxes than only type, then for each item in the short living list check the StringUserTrackers of the corresponding type for containing the item and remove from your short lived list those who don't.
Quite a significant cut down on operation cost if you ask me
that is pretty cool
Tho probably StringUsersTracker can further be abstracted to something like Tracker and accept as the key objects instead of only strings
Or Associator
@orchid bane @leaden solstice have either of you heard of https://redis.io/ ?
Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker
no
it might have all the optimizations that we were talking about in an open source
its a database on the memory, I have just learned about it
Redis is key value store not really does indexing or transaction for you like RDBMS
I dont raelly need a database, if there is no one online , its ok for my database/list to be empty.
so Im not sure and I dont really wanna benchmark everything, I just wanna use what is working.
and from my experience im a mayer of making mistakes, I rather not re invent the wheel, coz I'd probably fail lol
What I suggested only involves a few classes tho
The main issue of your structure is that you'll end up in race condition if multiple users trying to modify your list
Is your server gonna be single threaded
Yeah I love it, I dont mind making more classes, I will certainly use it in some project โค๏ธ , but if there is an open-source out there or a complete product that is trusted by others, I would rather go with that than anything I do myself ๐
Jobs carefully work around race conditions tho
What jobs
Im not sure honestly , its a relay server .. but probably yes a single threaded
He's talking about server
My friend created a few servers which work in unity tho
altough its made for unity, the server knows nothing about unity. Im sure of that.
it only collects requests and passes data
You don't want to use Unity for server with 15000 concurrent users
Speaking of that you probably also don't want to use single thread for it
its not , i hosted a relay server on Digital oceans , no worry
Quite a shame not to utilise Unity Jobs actually
but the relay already has list of those boxes so i thought maybe I could use it on the other hand I could use an actual database, from there I keept sniffing around for an answer
- Anybody?
I'm a bit new to unity. What would be the best option to make a multiplayer game? The game would host on device 1 and give a random code for other players to join on their device
Best option is subjective. They all are just variations to achieve the same thing. Unity's NGO, photon, mirror are all options.
None of these will do the work for you. Having a strong development background and understanding of networking is what's important.
Awesome, thanks!
I've got a question about coroutines and running additive scenes. I'm trying to use a fade to black and fade in during a scene transition. I'm running a coroutine to handle the fading down and up on my camera which exists on the player scene, separate from the scenes I am loading and unloading. The fade to black seems to work fine but fading back in never fires and the coroutine seems to die as soon as the scene transitions. Do coroutines die anytime a scene is loaded? I would guess it should only kill coroutines on scenes that were unloaded.
You should explain what part you are having problem implementing it. The answer for "how could I do it?" is just register as same as what you do for state to state transitions.
If the GO you are running coroutine didn't get unloaded then it should be still running
i need help again hehe
i created a new scene and now my hole progress is away how do i get it back?
Like in game progress or your scene wasnt saved?
yea
Yeah that's what I intended to happen. Maybe I'm misunderstanding how ownership of the coroutine works. I call the coroutine from a script on a GO that will be unloaded but the coroutine itself exists on the camera which is persistent and in my player scene.
i was making a game and then i ve got the idea to make a menu scene and then i clicked new scene and opend it, now i am in the new scene and i dont know how to come back
In this case does the coroutine then belong to the script that called it or the camera system which owns the IEnumerator?
Which is the object you called StartCoroutine?
Ah so there's my problem, I guess make a void function on the camera system that can start the coroutine
rather than starting it on the trigger that sends the player to the next scene
IEnumerator itself is not a coroutine and doesn't know it's owner FYI
It's only coroutine when you pass it to StartCoroutine
i was making a game and then i ve got the idea to make a menu scene and then i clicked new scene and opend it, now i am in the new scene and i dont know how to come back
Got it, ty for the clarification ๐
IS it possible to get my Scene back?
find the original scene asset in your project if you did not override it with the new scene
Locate the scene in the project files and open it
thank you guys
Always use version control too
I guess i can kill my self, the scene is not there
- As i mentioned, "type" is an abstract class. Currently, transitions are stored within a dictionary of
<Type, List<StateTransition>>. It works perfectly fine as long as i refer to it with a concrete, non-abstract type, but only then. I can post a script if you wish, but it's going to take long to see what it actually does. The most critical part would be
private List<Transition> GetTransitions(IState state)
{
Type type = state.GetType();
if (!_stateTransitionsRegistry.ContainsKey(type)) _stateTransitionsRegistry.Add(type, new List<Transition>());
return _stateTransitionsRegistry[type];
}
_stateTransitionRegistry is a <Type, List<Transition>> dictionary, which contains a collection of transitions per state type. It works perfectly fine with concrete classes, but i don't know how to make it gather results for all inherited classes as well
where is it?
I am not at your computer, so how could I possibly know
experience
Yes I have experience in where you locate your files
There may be a Scenes folder, it could be in there
You may even be able to search the project files like this t:Scene but I am not 100% sure
Hello, i remember that i somewhere saw animator parameter names as strings being converted to integer id's i think.
I want to do this right now but i can't seem to find the example.
Anyone know by any chance what the correct way was to convert a string to an integer id for the animator component?
i thought the animator component had a method for this but it seems not, as i can't find it
ah thanks i see why i couldn't find it now
You should check base class type with Type.BaseType or Type.GetInterfaces() and add them to derived types
Are Joint's angular limits (rotation) limiting the RB with Joint component, or the connected body's RB?
How can I remove a scene at runtime? I'm using SceneManager.UnloadSceneAsync(); on it but it remains
Also tried Resources.UnloadUnusedAssets();
Ok, I am participating in a game and there is a mechanic that is difficult for me to perform and I would like to know if you can help me in any way.
The mechanics consists in that the player, by pressing the space button, propels him to a point (in this case it is the green point) and then falls
Explanation
The idea is that when you move the green dot somewhere, the player will always push to where the dot is.
The trajectory predictor can be taken as inspiration.
But the difference is that the direction is handled by the green dot
Attempts
Tried to make the player's rigidbody2d translate to the green dot
through a vector3
Player.transform.position = Vector3.MoveTowards(Current player position, Green dot position, Movement speed * Time.deltaTime);
That makes it move to the green dot
Upon reaching the green point, the transfer code is deactivated so that the player falls
but it falls very hard
what is the best unity 2d and 3d scripting tutorial?
But I want a fall like this
If someone can help me, I would appreciate it very much, (And sorry for so much text but I think a clear explanation is necessary)
this decreases when its a negative when i put the same data into the same algo i wrote but in java it works :')
- Well, i rather need to check if class is abstract, and get all children in the dictionary if that's the case. I assume that base type method returns only a parent class?
Im referring to where it says y: for some reason it decreases
but when i write it in java it increases
BaseType returns direct parent of the type so you need to do it recursively.
when I enable a child gameObj, the parent transform seems to move
note that the parents transform position never changes and the child's transform is zero
anyone understand this?
thanks
Vector2[] doorsDown;
public Vector2[] getDoorsDown
{
get
{
if (doorsDown != null)
return doorsDown;
// ... calculate doors down
doorsDown = doors.ToArray();
return doorsDown;
}
}
Is this the right way to only calculate once a getter?
Seems ugly to me
public Vector2[] DoorsDown => doorsDown ??= doors.ToArray();
pretty
Well, the //... is because it has some lines
and that's not a getter, but yea, prettier
That is a getter
That is getter ๐
But if you need additional calculation the code you wrote seems correct
Okay, ty
I would note though that naming your variable getX is not a good naming convention. Name it what it is, and the fact that it's a property with a getter indicates the rest
The C# capitalisation conventions (that Unity hasn't historically followed, annoyingly) have public properties and methods as PascalCase, private as underscored _camelCase. So there wouldn't be any conflict between public and private names
Yeah, I'm too accustomed to write every method with camelCase
but I should try to change my mind when working with unity
Im trying to match a capsule collider along points A and B
getting some strange behavior
Which is point A and B?
A is where the collider is currently
which the parent gameObj is set to
point B is where the line renderer ends
who is parent?
change the direction of the capsule collider to Z
and position it at (pointA + pointB) / 2f
Or offset it by that distance
I could use it's center property for that yeah?
sure
I see thanks
Heres my understanding:
I put the capsule collider on Z which can be thought of as "forward"
then I rotate the gameObj's forward towards point B
fyi it's usually called PascalCase, Title Case, camelCase.
although I think you probably know that already
whoops, I knew that but made a mistake. Title and Pascal are the same are they not though?
Title has spaces
"This Is Title Case" "This is sentence case"
"ThisIsPascalCase"
impossible in code then ๐
Is there a way to disable the iOS keyboard from appearing automatically when in a text-input field?
public enum WeaponType{Dagger, Mace, Lance, Longsword, Catalyst};
if i had an enum for something like this. Is there a way to convert a simple int (that is within the count of the enum) into the respective enum?
(WeaponType)//index here//
var b = (WeaponType)1;
Output: Mace
How exactly does depenetration work? Suppose you have a capsule collider as your player, and a box collider as your wall. What are the steps to this? Not a lot of stuff online about this or I'm just looking in the wrong place
I need some help regarding scene management if anyone is familiar. Here's my issue:
I have a large sphere collider on my player that I'm using to detect nearby scene exits for additive loading. When the collider touches a scene exit I use SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive) and immediately set allowSceneActivation to false because I only want to activate the scene when the player's main collider actually touches the exit trigger.
It's working fine for loading, the problem is I'd like to remove the scene from memory and the hierarchy when the player's large sphere collider exits the scene exit trigger. How can I do this?
SceneManager.UnloadSceneAsync(sceneName); leaves the scene hanging in the (is loading) state. Is there a different way to kill an async operation or is there a better way to do this?
Hello, I need some help implementing spread to a shotgun in a 2D top down
I already did a rifle with a single shot without spread and this is how I'm starting with the shotgun but no idea how to do the spread in every bullet instantiate
for (int i = 0; i < ammountOfBullets; i++) {
Instantiate(bullet, bulletSpawner.position, bulletSpawner.rotation);
}
}
Also this is how I control the movement of the bullet, rb2D is the RigidBody2D of the bullet
private void FixedUpdate() {
rb2D.MovePosition(transform.position + transform.up * speed * Time.fixedDeltaTime);
}
you could just randomize the rotation
of the bullets
just add a random vector3 to the rotation's euler
bullet.eulerAngles += new Vector3(Random.Range(-range, range), Random.Range(-range, range), Random.Range(-range, range))
i believe you can do that
it wouldnt be as accurate tho
if you want like a perfect spread you can just set the rotation in the for loop where you instantiate them
have a float that starts from the left and goes to the right
and apply the rotation to each bullet
i mean if you're doing 2D then it would be a vector2d
and you would not need to worry about the other axis so only one rotation axis
I'll give it a shot, I don't want the bullets to have a perfect spread, more like a limited random spread for each
wait realized why
Anyone know how to do this? Iโve been searching but canโt find anything. Surely this is a common way to load/unload?
I have been working on my menu system, one of the options is the NewGame button
when I push the new game button the new game menu should appear immediately, I have to click it several times for it to appear initially, after that it loads instantly until the scene is reloaded (when entering play mode)
this is the code
this is how the component is configured
okay, what causes this? my render textures are like, 256x
My ps4 input is being detected as an xbox controller (and simultaneously a PS4 controller, so it's generating 2 inputs and really messing stuff up). This does not happen if I build the game and run it directly; only happening in the editor. I do not have DS4Windows or any other PS4 controller software installed. Steam is closed (though if Steam is open it is waaaay worse ๐ infinite inputs)
Hi! I'm experimenting with Mesh Deformation.
Would it be possible to change/blend materials based on vertex position?
For instance, let's say we have a flat mesh with a dirt material -- If one or more of the vertices were moved higher than their original positions, then that part of the mesh would blend into a more snowy looking material.
As well, similar could be done if said vertices were moved, instead, lower than their original position, blending into a magma looking material as opposed to snowy.
Any insight into this would be highly appreciated!
Could just have a fragment shader do that pretty easily.
Give it all the textures and you can write it to blend them based on world space height
That does sound good to me, I have just one question regarding that method -- Instead of basing it on world height, would I be able to base it on the meshes original vertex positions VS. modified vertex positions? Thank you for the assistance :)
I created a script called GameManager and it gave it a different icon. Did I just overwrite something?
nah its just default behavior thats been in there for years
i resolved it adding System.Drawing.dll and switching to .NET Framework api
I think it works with AudioManager too
I have decent experience with hex-level binary reversing and reading, but I've never encountered this issue before and it's totally confusing: I have a binary file (non-unity-standard file extension so I had to use an editor script to let me use it as a TextAsset) that has the beginning bytes as "52 42 53 50 01 00 00 00 AC 2E 7C 00". When I read the first 12 bytes and print out the bytes using the following code Stream s = new MemoryStream(MapFile.bytes); BinaryReader BR = new BinaryReader(s); byte[] hi = BR.ReadBytes(12); Debug.Log(BitConverter.ToString(hi)); I get the result "52-42-53-50-01-00-00-00-EF-BF-BD-2E" which is obviously not correct. Does the TextAsset conversion somehow modify the .bytes data or what could possibly cause an issue like this?
Maybe the TextAsset thing is causing it TextAsset subAsset = new TextAsset(File.ReadAllText(ctx.assetPath)); I can't just use ReadAllBytes instead though.. 
Nevermind, just adding ".bytes" to the end of the file name is required and fixed it.
It does not work.
PlayerSettings.stripEngineCode = true;
PlayerSettings.SetManagedStrippingLevel(BuildTargetGroup.Android, _stripLevel);
PlayerSettings.GetManagedStrippingLevel(BuildTargetGroup.Android)
It shows it is set but in the editor it is not.
I am looking into networking
NetcodeForGameObjects seems great, but if I wanted to, could I export my own dedicated sever? I know a lot of the server files are wrapped up in the client or even shared.
If I went for ENet... Could I re-use C# code between the client and server? It seems foolish to attempt to write the server 100% separate and assume zero overlap code with the client. And it's also very low level. Is it still feasible without all the high level stuff in NetcodeForGameObj?
I'm pretty sure NetCode allows you to have dedicated servers. Also, please discuss this in #archived-networking
perfect
?
What method are you running that code above in?
Hello, did unity remove the AddComponent method? If so is there an alternative to it?
AddComponent hasn't been removed, are you having any issues?
Yes, the method cannot be found in the normal unity assembly, I also cannot find it in the doc for component
๐
how do I get C# scripts to talk to each other? I'm trying to get two gameObject scripts to connect but I still get an error that such & such does not exist in current context so I know it's not working.
#๐ปโcode-beginner has Unity/programming courses pinned in the top right. That should get you up to speed.
ok, thx
if you want both to be called, you could have a reference to changetheweapon within weaponslot1selected
in the SelectMenuWeapon script have this line where you would have ints floats etc:
Public WeaponPickUp myweapon;
Then set it manually within the scene (You can also use GameObject.FindObjectOfType)
then you can use myweapon.ChangeTheWeapon() within the WeaponSlot1Selected function of the SelectMenuWeapon script.
Hello! Does anyone know if there is a way to check the character count in a InputField and how?
if you can get the string itself onto a script you can probably do <String>.Length
the <string> would be replaced by the reference to the string
if there is only one weaponslot1selected, have picking up a new weapon find said weaponslot1selected and call a function in it to set the "myweapon" from my example above
if there are more than 1 weaponslot1selected you may need a singleton or just a base character that can link the weapon to the slot somehow.
you seem to have "weaponE.ItemToDrop"
you can possibly use itemtodrop.Getcomponent<WeaponPickUp>().ChangeTheWeapon();
if you need reference to WeaponPickUp within the menu, you can try GameObject.Find();
putting the name of the weaponslot1 into GameObject.Find(); will return its gameobject and you could feed it data from the weapon itself.
ok so you need to find what weapon you're going to drop
if you have a "Weaponpickup" class within the weaponslot1's code [Public WeaponPickUp myweapon;]
then you can have a reference to your newest weapon
so whenever a new weapon enters slot 1 have it somehow get a reference to slot 1's script itself and fill the reference
<Myslot1>.myweapon = this;
whereas <Myslot1> is a the reference to the slot 1 gameobject
the gameobject and targets are in straight line , the gameobject rotation jiggles a bit when it reaches target object for a bit. even tho the rot variable and transform.rotation is depicting the same vectors of rotation.(bcz they are in straight line
then when the weapon is dropped just have
myweapon.ChangeTheWeapon();
within the drop script caused by the ui button press
anyone knows how to turn right a wheel thats already rolling forward?
i can turn wheel to the sides, or i can drive/roll it forward, but only one of these things.
when I roll wheel forward, 2/3 of its axes become useless for rotating, because theyre rotating themselves. So when I roll the wheel forward, its impossible for me to cleanly turn left or right.
transform.RotateAround(transform.right, speed);
or something like that
speed is whatever speed the wheel do be going
no the thing is transform.right rotates when u roll the wheel forward
ah try tranform up if you want to try to make it slightly rotate leftwards or rightwards
using transform.right rather than vector3.right alongside rotatearound will make the rotation be centered on the object rather than worldspace
both up and right rotate
i could help more if i had a snippit of your code to understand what you hav enow
at the end of the video u can see the train jiggles a bit . its rotation should not affect bcz gameobject and all target objects are in straight line . how to fix that?
somethings wrong about quaternion.slerp?
im a bit too tired right now...
you;re going to need some reference to what weapon is in each slot
like
public WeaponPickUp WepInSlot1
public WeaponPickUp WepInSlot2
public WeaponPickUp WepInSlot3
etc
then you can reference them
Dont make anything public unless other scripts need to access it. Serialize it instead
What exactly are you doing if you dont mind reiterating it?
You are trying to use WeaponPickUp as a singleton?
public virtual bool IsEnabled => enabled;```
Why does `IsEnabled` have only getter if `enabled` has both getter and setter?
One of my plugins has #if !NOT_UNITY3D, but I cannot find notions of this directive on unity website, can you help?
Surely Unity doesn't need to define a directive for not-Unity
Probably the plugin's mechanism for running it outside Unity
Do you think I can safely delete it?
Can't really tell without knowing what it does, but going by the name deleting the line would do nothing
and deleting the entire block would probably not be a good idea
Hi guys
The Issue is... I've attached a Application framerate target script in my scene to 60. (as mobile phones by default fps is set to 30)
but after that, My First Person Controller(built with character controller) when moving horizontally.... It jitters
when I set framerate to 30, the camera jittering problem goes away
what would be the reason? anyone faced yet?
Check the working of the controller
Jittering is usually connected to some things which should be in Update being in FixedUpdate
Or reversed
alright, let me try that