#archived-code-general
1 messages · Page 127 of 1
Is it a normal practice to launch many copies of same coroutine?
Will it cause some problems (except problem to store cache of all of them)?
Starting a coroutine creates a new ienumerator , so it's a new object(?).. you can have as many as you want running. It's also no problem to cache them, just cache in a list
You only need to cache them if you need the ability to stop them
Hi , does someone know how i can do some code every 5 scene changes? So basicly every 5 scenes i do something.
Just make an object that doesnt destroy on scenechanges and plus some int value by 1 every scene change and then do something
How do i make an object that doesnt destroy on a scene change
Thanks , im acctualy trying to display Admob ads every 5 scene changes (Interstitial) , however they dont show for some reason. Ill try do implement this DontDestroyOnLoad
You can just use a static int as a counter and increase it everytime a scene is loaded. No need for a DontDestroyOnLoad
Could you maybe give me an example of how that works?
Just a basic static variable
Watch this video in context on Unity Learn:
https://learn.unity.com/tutorial/statics-l
Statics are methods, variables, classes that aren't instanced. This means that methods and variables declared as static will belong to the class specifically and will be shared by all objects of the class. Classes declared as static will not be able to be ins...
I assumed you knew about statics because you asked in code general,not beginner
Basically static variables aren't tied to any instances(in this case GameObject). So when the objects are destroyed on scene change, it won't get lost
Then I hope you can Google how to detect when a scene is changed
Ok i kinda figured it out
@prime sinew How do i now Up the value of the public static int every time the scene changes?
same way you increment any int only you use the class name not an instance variable name
Hmmm , could someone try to see the problem here?
Heres my SceneTracker script
`using UnityEngine;
using UnityEditor.SceneManagement;
public class SceneChangeTracker : MonoBehaviour
{
public static int counter = 1;
public void Update()
{
if(counter % 5 == 0)
{
AdsManager.Instance.ShowAd();
}
}
}`
When the int can be divided by 5 show the ad
And at the start the int is 1
oh man why would you post a video in the middle of me showing my problem
jeez
oh sorry
its ok
yeet
Just a sec
have you try debug?
No
What kind of a type is a System.Single&
so where do you increment counter
So i up the value of the counter in my other script where i have all the levels of the game
So when a level is loaded
The int goes +1
static
that is the script we need to see
Its huge but heres the main thing
public void level1() { SceneManager.LoadScene("Level1"); SceneChangeTracker.counter ++; }
can static able to edit?
What does that mean
i thought static can not change
try switching those 2 lines around
oh i forgot
Alright
Doesnt seem to work
Thats funny
ye i dont even know how and why XD
also tried world to screen and somehow my object shaking
Dang these Admob interstitial ads are really getting on my nerves
did you add debug.logs into your script?
The one where i have my levels?
no the tracker
No
then how can you know what is not working?
1 in start to show the script is active
1 inside the if to show it's being fired
Hello.
I am currently using AudioTrack in Timeline to play sound.
When I pause the game, I set Timeline Speed to 0.
If I set the timeline speed to 0 while playing an AudioClip and leave it for more than 10 minutes, the AudioClip will not resume when I set the speed to 1.
Why is this?
may be it paused?
Well , the script definetly is active
Maybe i should put one to see if it acctualy ads the +1 to the int
maybe better rather than spamming the console to add some code to show a debug when counter changes
try figure it yourself
i have been figured my code why it is not working for a month
I understand that sound doesn't play when you pause.
When I unpause, the sound does not play.
If I call PlayableDirector.Evaluate, the sound will play.
so im trying to implement Discord RPC to my game and i tried a couple of times with the script being different everytime but nothing works, can anyone help?
using Discord;
using UnityEngine;
using UnityEngine.SceneManagement;
public class DiscordController : MonoBehaviour
{
public Discord.Discord discord;
void Start()
{
DontDestroyOnLoad(gameObject);
discord = new Discord.Discord(SOMEGAMEID, (System.UInt64)Discord.CreateFlags.Default);
var activityManager = discord.GetActivityManager();
var activity = new Discord.Activity
{
Details = "Some Details.",
State = "In " + SceneManager.GetActiveScene().name,
Assets =
{
LargeImage = "testicon",
LargeText = "SomeLargeText."
}
};
activityManager.UpdateActivity(activity, (res) =>
{
if(res == Discord.Result.Ok)
Debug.Log("Discord Status Set!");
else
Debug.LogError("Discord Status Failed!");
});
}
void Update()
{
discord.RunCallbacks();
}
}
then play it again instead
well sheet
just use script
screw it
so i did it
and wondering how to get rid of no need parts
might be there is another way to create that circle through scripts or some kind of funny layer
anyone know how to create circle or layer?
I figured out what i did wrong
Basicaly the GameManager script contains a list of levels where i put the int to go +1 , But that only happens when the levels buttons are clicked (im dumb) and so i tried clicking 5 level buttons and it worked .
Now i have a diffrent problem
nice
Nice , now it works when i click the continiue button which i wanted in the first place
The only problem is that the ad gets displayed for a split second and dissapears
and it pauses my game as i can see
Hey all, I understand that a child can override a method in an inherited parent method with virtual / override, is there a version of this where instead of overriding, it calls both? so when Method() is called in the parent, the child of the parent class then does something extra on top of Method() (without having to add SendMessage or anything in the parent). Thanks in advance hope my question makes sense.
the child can invoke the parent's method
but you can't force that to happen (without using reflection, at least)
You're not wanting override but shadowing. This can be explicitly stated by using the new keyword with the method definition.
override void Example() {
base.Example();
// More stuff
}```
I don't think Dalphat understood the question properly TBH
Hiding the parent method with new will not be called at all when you invoke the method from a reference of the parent type
Thank you that makes a lot of sense, I'm overriding it then also calling the base function resulting in both working together.
@leaden ice 's answer solves your problem. If you want to FORCE the parent class to run regardless of the child class implementation, what you can do is
public void Foo()
{
// Do Stuff
OnFoo();
}
protected virtual void OnFoo() { }
have you did it?
And override the OnFoo instead
Yeah, I wasn't sure what he wanted and was going to suggest calling the base implementation but figured he might simply be wanting shadowing. Reading again, he stated that the method should be overridden as it's being called from a reference of the base.
I misread it stating that he wanted to be able to call both individually from a method - the misinterpretation.
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
https://gdl.space/dojujesubu.cs -- Flashlight script
https://gdl.space/deqamaweto.cs -- Flashlight Battery script
Im trying to have my flashlight turn off when the flashlightBattery == 0, but my flashlight wont turn off and the battery UI wont disapear.
If it's a float and computed, it might not ever possibly be equal to zero.
look at line 42, then look at line 33
yea I had to make the value less then 0, so then when the flashlightbattery == 0 the flashlight turns off
when I did >= 0, it had the same problem
0 is an int 0f is a float
ohhhh that might be it my stamina drain is not like a perfect even number such as 20 so it might never equal 0
that would fix it?
no, you should never check floats for equality
howcome ?
because of float imprecision. 0.0000001 is not == 0f
10f/2f likely isn't 5f
If anything, you could try https://docs.unity3d.com/ScriptReference/Mathf.Approximately.html
I'm trying to think of a way to make sure premade rooms are rotated in the right direction for their openings to match. I'm not sure how to implement a system to do this
//If battery level reaches 0 we turn off the flashlight
if(Mathf.Approximately(0,battery.flashlightBattery))
{
off = true;
flashlight.SetActive(false);
}
I used Mathf.Approximately, but it still does the same thing
the flashlight wont turn off
Log the value of the battery before that if statement
See if it's what you think it is
You have to check if it's < 0 because there's nothing that would stop it from going below that
if (off && Input.GetKeyDown("f") && battery.flashlightBattery > -0.1)
{
flashlight.SetActive(true);
//Turn on sound here
off = false;
on = true;
//If battery level reaches 0 we turn off the flashlight
if(Mathf.Approximately(0,battery.flashlightBattery))
{
off = true;
flashlight.SetActive(false);
}
}
this is the whole thing
also the check is in a block that requires that battery.flashlightBattery > -0.1 so it has to be exactly between -0.1 and 0 which is very unlikely
if the battery is greater than -0.1 then it turns on
I was assuming he was okay with negative values
What if it's -10
None of the statements would occur
I dont understand that if my batteryDrain is 10f it would have to equal 0 at some point
if my max battery life is 100f
no it doesn't
so I should prnt out of current flashlightbattery to see what its doing
ok let me do that
Yes and to see if it actually even gets there
and this check requires that you've pressed the f button on the exact frame when the battery is exactly 0
there's so much wrong with this logic
will using goto to go to the top of a function cause recursion?
also why do you have separate on and off variables, makes no sense
doesn't it check if the battery == 0 when you've already pressed f
@stark jacinth Maybe clamp the battery value
@stark jacinth If the step (drain * deltaTime) is greater than your epsilon, there's a chance it'll skip that range and you'll miss that condition.
Instead of subtracting, use Mathf.MoveTowards(), this will ensure you never skip your target value
it checks it when the condition off && Input.GetKeyDown("f") && battery.flashlightBattery > -0.1 is true
if you're not pressing f then it's not true
well yea if your battery life is less than 0 you cant turn on the flashlight
and while you've already turned on the flashlight as the battery is draining if the battery equals 0 then it shuts off
then why is the check that turns it off inside that check?
because when you turn on the flashlight the battery starts draining
if it equals 0 your flashlight is dead
so it turns off
but only if the key is pressed
Yes, that's what you're trying to do, but that's not what the code does
His point is that this will never fire unless the user is pressing F down at that exact frame
Maybe take the turn off feature out of the turn on key press
where is that?
In your update
ohhh
You're only attempting to turn off when you turn it on - not while it's on
it has to be off to turn it on
irl what happens to a flashlight if you turn it on and just leave it?
it eventually dies out
yes, no keypress required. so why are you checking the battery only when there is a keypress?
didn't we go over this yesterday
Is there a way to rotate the Z axis to point out the doorway for me to use that as a forward check?
the battery should drain in Update, not in the function that's only called once when you turn it on
jesus christ
you have
if (off && Input.GetKeyDown("f") && battery.flashlightBattery > -0.01) {
if(battery.flashlightBattery == 0) {
...
}
}
it should be instead
if(battery.flashlightBattery < 0) {
...
}
else if (off && Input.GetKeyDown("f") && battery.flashlightBattery > -0.01) {
...
}
oh, i suppose you did change that
it's the same kind of issue, though: you should always check if the battery is dead
not just checking when you actually try to turn it on or off
@mellow sigil We all started somewhere, breathe
if (Input.GetKeyDown("f") && battery.flashlightBattery > 0.1)
{
if (off)
{
flashlight.SetActive(true);
//Turn on sound here
}
if (on)
{
flashlight.SetActive(false);
//Turn off sound here
}
}
//If battery level reaches 0 we turn off the flashlight
if (Mathf.Approximately(0, battery.flashlightBattery))
{
off = true;
flashlight.SetActive(false);
}
what about this logic ?
if you press f and off is true it turns on
vice versa it turns off
but if the battery equals 0 then the flashlihgt turns off
if button pressed and is off and not battery empty
turn on
else if is on and battery empty
turn off```
if (off && Input.GetKeyDown("f") && battery.flashlightBattery > 0.1)
{
//Turning on flashlight
flashlight.SetActive(true);
//Turn on sound here
}
else if(on && Mathf.Approximately(0, battery.flashlightBattery))
{
off = true;
flashlight.SetActive(false);
}
if(on && Input.GetKeyDown("f"))
{
flashlight.SetActive(false);
}
like this?
I think you should try what you had before
this
?
if you must use 2 bools you also need to set on to false when the battery is drained
although I see absolutely no reason for doing so
if (off && Input.GetKeyDown("f") && battery.flashlightBattery > 0.1)
{
flashlight.SetActive(true);
//Turn on sound here
on = true;
}
else if(on && Input.GetKeyDown("f"))
{
off = true;
flashlight.SetActive(false);
//turn off sound here
}
//If battery level reaches 0 we turn off the flashlight
else if ( on && Mathf.Approximately(0, battery.flashlightBattery))
{
off = true;
flashlight.SetActive(false);
}
I wrote this and it still wont turn off when the flashlightbattery equals 0
instead of
if ( on && Mathf.Approximately(0, battery.flashlightBattery))
why not just
if ( on && battery.flashlightBattery < 0.01f)
ok this turned off the flashlight
did you also set on to false?
else if ( on && battery.flashlightBattery < 0.01f)
{
off = true;
flashlight.SetActive(false);
}
well yes
no you didn't
i see no on=false; there
oh just becasue off = true doesnt mean on == false;
@stark jacinth Hey, you have 2 different variables to track a single state that can be represented by a binary value. This is awful design, will confuse you and get the best of you.
you made 2 bools where 1 is enough
but good news it does work, thank you Steve I really appreciate it
How to set the asset bundle that an asset is in automatically?
Is it me or is the Range attribute very buggy? When setting the number manually, it fails to save if I click away. Furthermore, if I drag the slider, the nob tends to randomly disappear at higher (but inside the range) values. Very confusing. I feel like this didn't used to be a thing, is there something borked on my end or is this normal?
Thanks foo, I didn't know it when I asked the question but this ended up being what I was actually trying to do
Is this a code question or #📲┃ui-ux
I mean... little bit of both, I suppose.
Depends on what the answer is lol
What? Show the code which relates to this then
Literally just [Range(0,1)] public float someValue;
Just wanna know if it's normal for it to behave like that, feels pretty buggy
behave like what , still don't understand what you're seeing
can u make a vid?
In the inspector, this produces a slider and a field. If I drag the slider, it saves just fine. If I manually enter a value and switch away, it resets, basically
Uhh, guess I could, if it's still not clear, just currently eating :P
never had that happen
sounds broken/bug . what verision of unity ?
2022.3.0f1
not surpised 😛
Yea, I seem to remember this not being a thing as well 🤔
3.0 been buggy for me, maybe try latest
This whole project is becoming more and more cursed lol
Hm. Yea, maybe not the worst idea 🤔
Im personally still on 2021 because i dont trust 2022 yet until a few patches later 😛
Well, I'm one of those crazy DOTS people, so...
DOTS works on 21 though no?
Yea, some versions :P
I mean, I jumped on LTS because that's supposed to be where DOTS comes together
But here we are
Either way, RangeAttribute randomly breaking would be such a weird bug... I think something is just borked with this entire project, I've been getting strange ghost problems for a while now
Gonna update now and maybe do a full reimport or something and see where that lands. Thanks for confirming that I'm not crazy and this is not normal 👍
@wintry schooner I would try the project in a later version of unity (make sure you backup)
see if it's reproducable / fixed @wintry schooner
2021 is still LTS 🙂
Hm. It's fixed now 🤔
I refuse to believe that the version bump did it, that's just such an odd thing to break 🤔
Although... upgrading probably reimports as well, right? If so, that's probably what did it. Maybe this project just uncursed itself.
yeah hard to say what fixed it at this point. I just know 2022.3.0 was buggy for me
like adding a new script would not make it attach to gameobject
then i get the "All errors must be fixed before attaching script.. bla bla"
spoler alert: there was no error from a new script..
so I had to restart to make it work
i'm gonna wait for another minor release or two
i do still have some...problems on my macbook
yea is best to wait a bit
sometimes the console starts spamming "BeginWrite after EndWrite!!!!"
sometimes it crashes when exiting playmode
3.0 or recent ones?
haven't tried 3.2 but its out already
dont see the release notes tho oddly nvm its here today
I need a little bit of networking🤓 help. I need to make smth like a gallery that will load images from server and display them at runtime. It should get them by URL and they're indexed, like: "http://data.ikppbb.com/test-task-unity-data/pics/33.jpg". And I want it to support any amount of images. Is there any way to know the number before it starts getting the actual image data? Because I wanted it to instantiate the exact amount of images and load textures asynchronously, but for me it looks like its impossible. You either have to know the exact number of them, or send 2 requests: 1st checking if the ardress is valid and 2nd to get the texture, but what I see is that it is pointless and negotiates all the performance gained by async calls 🤔
Texture2D lastValidTexture;
int currentIndex = 1;
private async void Start()
{
do
{
lastValidTexture = await URLDataRetriever.GetTextureFromURL($"{_url}{currentIndex}.jpg");
if (lastValidTexture == null)
return;
RawImage image = Instantiate(_imagePrefab, _content.transform);
image.texture = lastValidTexture;
currentIndex++;
} while (lastValidTexture != null);
}```
Thats what I came up with by far
https://unity.com/releases/editor/qa/lts-releases
patch notes for 3.2 fially here
2 days later 😛
nah, 2022.2.x
oh wow thats not even LTS is it?
same but i tried LTS and it failed
is this a server that you control? if so, just give it an API endpoint that tells you how many images there are, query that before getting the images
wow lots of buug fixes in 3.2 tho
splines package is just too good 😛
{
public Image ımage;
public Camera cam;
public float sensitivity = 2f;
public float SmoothSensivity = 2f;
private Vector2 initialTouchPosition;
void Update()
{
for (int i = 0; i < Input.touchCount; i++)
{
Touch touch = Input.GetTouch(i);
if (touch.phase == TouchPhase.Began)
{
initialTouchPosition = touch.position;
}
if (touch.phase == TouchPhase.Moved)
{
if (!RectTransformUtility.RectangleContainsScreenPoint(ımage.rectTransform, touch.position))
{
float x = (touch.position.x - initialTouchPosition.x) * sensitivity;
float y = (touch.position.y - initialTouchPosition.y) * sensitivity;
Quaternion characterrot = Quaternion.Euler(0f, x+transform.eulerAngles.y, 0f) ;
Quaternion camerarot = Quaternion.Euler(-y, 0f, 0f);
transform.rotation = Quaternion.Lerp(transform.rotation, characterrot, Time.deltaTime * SmoothSensivity);
cam.transform.rotation = Quaternion.Lerp(cam.transform.rotation, camerarot, Time.deltaTime * SmoothSensivity);
}
}
}
}
}```
Hello, in this code I want to rotate my character and my camera under my character, but I couldn't get a precise mechanic exactly as I wanted, can you help me?
Yea, add general ECS weirdness to the mix and I'm sure you see what I mean by "it's cursed" :P Let's see how long it works now.
Nope
Resolved.
Thank you very much.
you're using lerp incorrectly https://gamedevbeginner.com/the-right-way-to-lerp-in-unity-with-examples/
thank you
the what who now?
whats a thred requests
Oh you shouldnt be checking for Input in FixedUpdate() i also believe that you dont need Time.fixedDeltaTime on anything that has to do with movement in FixedUpdate()
Check for input in Update()
You shouldnt be doing alot of this in FixedUpdate() honestly
Its Physics based so theres no reason to Play audio or set animations in there. You should really only be doing stuff with anything thats Physics based IE just the Rigidbody
You also need to set the interpolate mode to Interpolate rather than none if you havent done so already
You do want to use fixedDeltaTime. Otherwise, your movement speed will be 50 times higher than expected.
(or whatever the physics update frequency is)
Really ? isnt that kind of redundant since FixedUpdate already runs 50 times a second ? @heady iris
I may be wrong tho
Well, sure
but
void FixedUpdate() {
rb.MovePosition(Vector3.right);
}
this will move you at 50 meters per second by default
probably not what you wanted
(also Time.deltaTime will be equal to Time.fixedDeltaTime in the context of FixedUpdate. very handy)
For 2D platformers where once you hit spikes/bottomless pits you get teleported back to the last stable ground you stood on, do games generally remember where you last stood safely or have invisible checkpoint triggers?
I can see the pros and cons of each but I feel like the former should work right?
the former is easier to generalize
you just need a way to define a stable surface
probably any situation where you're on a non-moving collider and aren't being pushed by it
(i.e. you aren't sliding off a ledge)
Mmm yeah I imagine I'd probably do something where it checks for a wide enough open space around the player every frame
When saving keybindings in playerprefs (I have 13 right now) would it be best to just save them all as one string and parse it on read?
Individual feels kinda silly
Then yeah I'd probably make it so "ground" by default saves the position, but for certain grounds where I don't want it to save what would be the best way to check? A component class, tag, layer, something else?
I've had an idea for a while of making a class thats main purpose is to hold loads of tags as strings. Then I could just put it on everything I want to have tags. Only problem is calling GetComponent as it's fairly slow I think. Might be faster to make some sort of tag manager dictionary thing? Maybe I'm overcomplicating everything now
i might add trigger colliders that forbid you from saving your position there
It's absolutely not redundant. Imagine this piece of code:
float movementPerFrame = 1;
void FixedUpdate() {
rb.MovePosition(Vector3.right * movementPerFrame);
}```
So now we're moving 1 unit every fixed update. Sure we don't need deltaTime to adjust for varying framerates. But there IS still an uncontrolled external variable here, and that is the fixed timestep. By default it's 0.02 (1/50), but you can change it. Let's say we go to the menu and change it to 0.01 (1/100) because we want more accurate collisions. Now suddenly even though the code has not changed at all, we're now moving 100 units per second instead of 50.
It's much better to do this so you're absolutely clear in the code about how far you're moving per second:
```cs
float movementPerSecond = 50;
void FixedUpdate() {
rb.MovePosition(Vector3.right * movementPerSecond * Time.fixedDeltaTime);
}```
Now it doesn't matter what you change the fixed timestep to in the settings, your object always moves the same realtime speed no matter what
aaahhh i see now
It's also a lot easier to think of things in terms of "per second" than "per fixed update frame"
Thank u both that actaully makes sense
indeed: analyze the units
if something happens every frame, then the units are "per frame"
if you move 1 meter, then that's "1 meter per frame"
If anyone has any thoughts on my post just above that would be fantastical, I am very new to C#
to get to meters per second, you'd have to divide by deltaTime, since deltaTime is "seconds per frame"
and surprise! you're actually going at like 50 meters per second
Is this a stupid idea?
public class ManagerTags : Singleton
{
public Dictionary<string, string[]> AllTags = new Dictionary<string, string[]>();
public void AddTag(string ID, string[] tags) => AllTags.Add(ID, tags);
public bool CheckTag(GameObject gameObject, string tag)
{
if (!AllTags.TryGetValue(gameObject.GetInstanceID().ToString(), out string[] tags))
return false;
if (tags == null)
return false;
return tags.ToString().Contains(tag);
}
}```
Anything with the Tag component can store multiple tags, and during Start() adds its tags to the ManagerTags
From then on anything can check if a gameobject has a tag by calling:
Get<ManagerTags>().CheckTag(gameObjectExample, "NotStorePosition");
Dumb or genius?
It's a fine idea in general but you could optimize it a lot and make the programming interface a lot easier to deal with
I'd love to hear your suggestions
Just a few quick ones:
- Use
intinstead ofstringas the id/key type. It will be faster and use less memory (and create less garbage) - Use something like a multi value dictionary instead (example here: https://github.com/SolutionsDesign/Algorithmia/blob/master/SD.Tools.Algorithmia/GeneralDataStructures/MultiValueDictionary.cs)
- Make extension methods for GameObject like:
public static class TagExtensions {
public static bool HasTag(this GameObject obj, string tag) {
ManagerTags.Instance.CheckTag(obj, tag);
}
public static IEnumerable<string> GetTags(this GameObject obj) {
return ManagerTags.Instance.GetTags(obj);
}
}```
This will let you do like `if (gameObjectExample.HasTag("NotStorePosition"))`
All great stuff thanks a ton!
Another thing to consider is you will want to figure out how to clean up destroyed objects too
when an object is destroyed you will probably want to remove all the tags you stored for it, or you'll have a memory leak
not just because you'll be remembering tags, but also because that object can never be GC'd
since a reference yet remains!
basically I'd just put an OnDestroy on your Tag component
which will remove it from the manager
Hm alright thanks, btw so is the multidictionary faster than just storing an array?
should be the simplest approach
the one I linked uses a HashSet under the hood which will be faster than an array yes, because it can be resized (rather than discarding the whole array when size changes) and also the Contains checks may be faster if you have a lot of tags.
note that HashSet ultimately uses arrays too, but it manages the memory a bit better than if you just discard the array to resize.
I think I need something called UtilityClasses which is within the Algormithia repository, am I able to just download the folder straight from github somehow? Or should I be downloading all of it from github/somewhere else?
public static Vector2 GetPivot(this PolygonCollider2D collider)
{
Vector2[] vertices = collider.GetPath(0);
Vector2 center = Vector2.zero;
foreach (Vector2 vertex in vertices)
{
center += vertex;
}
center /= vertices.Length;
return center;
}
I want to find out the center point in such an object, I do it as in the screenshot, but somehow the center was somehow not accurately determined
you can just throw scripts into your Assets folder, yes
yes, beacuse there are more vertices on the right side of the collider
sounds like you want the center of the bounding box.
collider.bounds ought to be relevant
What do you mean it can be resized faster ?
Is there a way to do it from the website that I'm not seeing or do I need to use git bash or something?
Are there any good solutions for making a calculated property readonly & visible in the inspector? IE:
public float Speed => 1f + 1f;
i'd just download a zip from github and then throw the contents into Assets somewhere
I can't (don't want to) make a backing field that I set internally - I would rather this be a calculated thing
Specifically I have a component that has a single tween (reveal/hide) and I'd like to be able to see a property of "is animating?" without setting a backing field whenever I start/stop the tween
you need custominspector
- You can create a wrapper around your property and do a PropertyDrawer
- You can use CustomEditor (Draw the default for the rest)
ay-yah
Maybe something like #archived-code-general message
Yeah I'm trying to limit my .. attributes in this project and custom drawers. I suppose I could go that way, I was sorta hoping there were a more generic solution rather than needing to make a drawer for each instance that I'd need this
Especially because in this case it's just a bool
See how I override the CustomEditor of MonoBehaviour
Like, this is what my current "solution" looks like and .. I hate it:
private Tween _tween;
[UnityReadOnly, SerializeField] private bool IsAnimating = false;
.. any place I kill the tween:
_tween.Kill();
IsAnimating = false;
.. any place I start the tween:
_tween = .... some stuff ....Play();
IsAnimating = true;
.. and then a custom update:
private void Update()
{
if (IsAnimating && !_tween.IsActive()) IsAnimating = false;
}
Yeah your solution works but I'd have to write one of those drawers for each property I wanted .. I was sorta hoping there were a generic solution that I could write an attribute for without getting too fancy with the reflection
I imagine I'd have to write an attribute that takes a string parameter with the name of a method, and call that or something. Not really simple and might be a bug surface
No. Not if you do CustomEditor on MonoBehaviour. You could even do it without reflection.
Reflection is just more pratical
huh. i never thought about doing that.
[Inspect] private string IsAnimating => ...;
The issue, is that it will be under or over the rest.
If you want to make it in, you will need to redraw everythings.
That being said, that shouldnt be hard.
well, you've probably gotten the game object from a component before
in fact, that's what gameObject.tag is doing
every component has a .gameObject property
ya
https://www.youtube.com/watch?v=waEsGu--9P8&t=0s
guys i am trying to add a pathfinding algorythm to my game and i am following this video but i dont understand what he is doing, he me made a grid class in the beginning of the video do i need to make a grid class i mean i have a mapGenScript which generates a random map use procedural gen and i use a multidimensional array there i dont if i even need the grid class he does could someone explain to me whats going on here?
✅ Get the Project files and Utilities at https://cmonkey.co/gridsystem
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
Let's make a Grid System that we can use to split our World into various Grid Cells.
Then we can use that to make a Heatmap or a Pathfinding Map with avoid/desire areas or a Building Grid System.
Complete Grid ...
Anyone know why these two instanceIDs are different?
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.TryGetComponent(out ContactDamage contact))
{
Debug.Log(contact.gameObject.GetInstanceID()); // 1
}
}
public class Tags : MonoBehaviour
{
private void Start()
{
Debug.Log(GetInstanceID()); // 2
}
}```
The gameobject has two main components, ContactDamage and Tags
How could these instanceIDs be different even though it's the same gameobject?
beacuse GetInstanceID() is a method of UnityEngine.Object
you can call it on anything that's a unity object
GameObject and MonoBehaviour are both objects
Ah I see whoops
GetInstanceID() down there is being invoked on your monobehaviour
up top it's on a game object
What is the best practices regarding extracting methods?
I have pretty big class with long functions in it. I divided this functions to multiple ones, but where should I store them?
Static helper class? Maybe non-static class which I initialise with parameters to avoid passing the same variables to all its functions? Or maybe I shouldn't use another class at all and there are better approach to this?
you need ordering?
probably you should consider using #region then
It really depends on what you are doing.
You should try to follow the SOLID principle.
There is just a bunch of logic, event invocations, calculations of parameters that I am passing to events
You will need to be more specific.
Checking collisions, mapping them, filtering collisions, caching needed components of collided objects, invoking events for collision, damage calculation for each collided object, invoking damage events, applying damage, finding position for spawn another objectm instantiating this object, etc.
It's not like I am doing, for example, "applying damage" in this function, I am just calling a couple of functions from corresponding class, but still there is a lot of code in this class, so I want to know where should I extract new functions.
But that way code still would be in this file. I don't want classes hundreds of lines long
Still, I would need to see the code to make any suggestion.
oh, unity source classes are probably quite long too 🙄
and no, I does not mean that your classes should be the same
They are doing an Engine also.
There is a lot of function that are variation of others
maybe @hollow hound is also doing an Engine
From what I understand, it is not the same as doing 5 function override.
Hah, no
However, I cannot know because I do not see anything.
We can even start with 1 function.
@hollow hound probably namespaces should help you somehow?
if you add a new tag to an element in a hashset that's a lot faster than creating a whole new array, copying all the old tags over and adding the new one, and throwing the old tag array out
arrays can't be resized
My bad I though he was using a list.
Because a list would behave the same.
But namespace should contain the class, not just function, right? So the question is, should I use static or non-static class for this? Or maybe something different
The hashset also has the advantage of not allowing duplicates
It depends on what you do.
Yeah, or having nightmare Hash collision.
hash sets and maps handle collisions.
er, hash maps do
i would expect the same from hashsets
It looks something like this:
void HandleCollisions(...){
var collidersInfo = GetCollidersInfo(...)
foreach (var colliderInfo in collidersInfo) ProcessCollision(...)
}
MyClass[] GetCollidersInfo(...){
// dozens lines of code
}
void ProcessCollision(...){
// dozens lines of code
ProcessOnHitLogic(...)
}
void ProcessOnHitLogic(...){
// dozens lines of code
}
The question is, where should I put this GetCollidersInfo, ProcessCollision and ProcessOnHitLogic?
Their logic is specific for this class, they are called only from one place each.
Hey guys, I am developing a mobile 2D game and for some reason when I use unity remote 5 on my IOS and play the game, it's getting low fps and very blurry/pixelated. I have tried to put the spirits on the "point (no filter)" mode and fixed so the resolution matches the screen, what could be the problem?
You could first, divide the concept of collision and the concept of reaction.
Have one component that does the collision processing, while other listen to this one.
What you mean by "concept of reaction"?
Multiple object might react to the same collision event.
At least, I would expect.
However, because I do not know nor see your code, I cannot know.
So you're just trying to organize your class so it's cleaner?
Yes, there is some event invocations for them in this "dozens lines of code"
through bound it doesn’t find the center very accurately, I want exactly where the yellow dot on the screen is approximately
Make your class a partial, and split it into multiple files
Oh god, please do not make partial.
you want the center of mass.
What are those events.
- Does this work in builds of the game?
- Is this a terrible idea?
BoxCollider2D _col;
private void OnValidate()
{
_col = GetComponent<BoxCollider2D>();
}```
I did this once. I split my big class into five partial classes.
It was awful. I couldn't remember where things went and it was way worse than the original experience
i have since factored out big chunks into a state machine
this is non-trivial to compute in general. not sure what i'd do here.
No, onvalidate is editor only.
Use Awake
Not good idea as you might have object that have not been inspected at Runtime.
yes, but I found it like that above, but due to the uneven arrangement it counts unevenly
My idea here is that all components are assigned in the editor so:
I don't have to assign them myself with dragging and dropping (SerializeField method)
It reduces time to load scenes and improves performance (GetComponent method)
this has nothing to do with scene load time
and also nothing to do with performance
BoxCollider2D _col; < this field will not be serialized
The performance impact should be minimal.
I feel like unity should also provide a center of mass for colliders 🤔
so that assignment will not make it into the build
serialize the field and you can assign in Reset and/or OnValidate and it will keep the reference when you build. however it will not work when adding components at runtime
If I do [SerializeField] will it save?
yes
Bad idea though?
Use OnReset for this purpose
Not onvalidate
Nor for component that have not been inspected in a scene as far as I know.
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
the function? you wanna divide the function?
and yes, late reply, sorry
i gotta ask, why do you use that command in this channel just to then post your code in another channel? you know you can use the command in the channel you intended to post your code in. or even just bookmark one of the bin sites since you use the command so frequently
dividing the function means making it virtual
Events like "onHitboxCollisionEnterStart", "onFrameCollidersEnter" that other classes listens to. It's pretty complex system, and I don't think I can explain it in reasonable time. In short, this is class of weaopn behaviour. HandleCollisions calls GetCollidersInfo that filters and caches colliders. ProcessCollision invokes multiple events for triggers, calculations and damage receiving, it also calls ProcessOnHitLogic that handles spawning another entities with more logic.
I wonder where should I store those functions, because this class is already 350 lines long and growing quickly
usually ive already written out my question, so i dont want to delete it all, and my instincts tell me to go here
- 350 lines is nothing
- Use component to divide the behavior
- Add intermediate concept such as Hit, Filter, Triggers, Actions, Effects, Attacks, etc.
- Follow the Single Responsibility principle
Why component? I don't want instantiate it or something, it's pure logic in this functions.
Where should I store Hit, Filter, Triggers, Actions? In one class? In multiple classes? Non-statiс classes that are initialising with parameters or static in functions of which I should pass same/similar parameters?
There is always a limit of "Single Responsibility". Or should I make a new class for all this functions?
I do not know because I am not in your project. You are asking question that I are situational base on what you are actually doing.
- Component does not need to be instantiate at runtime.
- It depends on what you currently have. They could be in a separate class.
- Single Responsability is single responsability. You described multiple responsibility in what you are saying, so I guess it might have not been correctly applied.
However, I cannot know for sure what can be modified without seeing actual code.
Ok, thanks for the hints
hi, is there any difference between ObjectPool.Clear() and .Dispose()? just trying to confirm if the docs are right, 'cause they have the exact same description
they are identical. Dispose just calls Clear()
https://github.com/Unity-Technologies/UnityCsReference/blob/18e481fd5dbda630b82f4f4c59a2a0164ed75ebd/Runtime/Export/ObjectPool/ObjectPools.cs#LL162C19-L162C19
i see, thanks
the reason both methods exist seems to be because of the two interfaces. It implements IDisposable so that's why it has the Dispose method, but the IObjectPool<T> interface has a Clear method which is better named for what its purpose is
ah, it does? i went looking but didn't see IDisposable mentioned
oh yeah, there it is in the reference
it's not mentioned in the unity docs
yeah i noticed that, kind of odd that it isn't mentioned there
but there's plenty of objects with undocumented behavior
correct. there is no off topic channel in this server
There is no way I can implicitly inherit a constructor, right?
Like:
public class A
{
public A(int num)
{
}
}
public class B : A
{
}
It won't work because I have to explicitly declare public B(int num) : base(num){}
Is there a way to avoid this? If not, I wonder why is it made this way.
Like when I create B, it can check constructors with given params in child and parent class, what am i missing?
because derived classes want to retain the ability to constrained/simplify the ctors they provide, it would get out of hand quickly if you'd inherit all constructors of base types. even just the parameterless ctor of the base object could get annoying.
So it is made this way to give opportunity to, for example, use only 2 constructors from base class and not all 8, right?
its made so you can constrain ctor options in derived classes
By ctor options you mean different constructors?
yes, or different signatures and defaults you might pass on to the base
Hey, I invoke an action when a node selected on a grid.
I have 3 situations for now but i may have more in the future.
If I selected a building from the UI i should build it.
If i didnt select a building and theres a unit on the node i should select the unit and display it on UI
If i didnt select a building ad theres no unit on the node then i just return or do something else.
How can i build this without breaking solid principles and being able to extend it later on
e.g. you can do public Foo() : base(default) {} to add a parameterless ctor or private Foo() {} to remove the parameterless ctor that may be on the base
Thanks
how can I make UI looks the same on all devices?
In Canves settings I use Scale with screen size, but no idae what should i use for Reference resolution. My game is 9:16 on mobile
The reference resolution matters for your imported art, so you can match the scale.
If this means nothing to you, then just use a common resolution like 1920*1080 and keep it consistent across all your canvases.
Has anyone had this editor draw call issue where serialized classes in lists or dictionaries are not changing the size of the editor elements?
Seems to happen to all my serialized classes in 2021
thanks
When i set it on 1920*1080 it looks very small on the editor's game tab, is it normal?
Yes, so you make the UI how you want it to be.
dictionary in inspector? that's not a thing
If you knew the scale your assets were made in, you would use that resolution and choose the Set Native Size button on things like images.
Anyway. This isn't a coding question. #📲┃ui-ux
sure sorry
update your editor. this was fixed months ago (almost a year ago actually)
does anyone know how I can make it so that when i switch cameras, the player doesn't doesn't like whip around? What i mean is, when the player is in the free look camera mode and the camera and player model are facing in oposite directions. then when the player switches to the backview, the player model faces where the free look camera was facing before
Feature. No one can help you without seeing the code.
https://dontasktoask.com/
are you talking to me?
thats my code
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
if only there were instructions for large code blocks
funny too, because inline isnt even the first part of that command
Doesn't with for all platforms
it learns
it?
so you want the rotation to be gradual ?
yes? i think
for example, if the player is in the freelook camera angle and the camera and player are facing opposite directions. Then if the player switches to the combat camera, the combat camera should look to wherever the freelook cmaera was looking and the player should face that way too
isn't that what you're doing already
i get it
cool
what component is the virtual cam
wdym virtual cam
what mode rather
?
the freelook camera is basic and the combat is combat
if thats what you're asking
no like show the virtual cam cinemachine component
combat camera
you want it to match the previous rotation from freelook yes?
yeah
it should be as easy as storing the camera's rotation before the switch them rotate with the variable you stored
If I set a string to public (or serialize it to show up in the inspector), how can I put line breaks in the field in the inspector?
but it matters which virtual camera mode you have set for Look/ Body
some mode lock rotation
im a still a little confused on what you mean by the virutal part
wdym you're using Cinemachine ye?
yeah
do you not know what a virtual camera is ?
not really
oh..can you screenshot the inspector for combat camera
do you want me to send you this
MultilineAttribute, but honestly this was 1 search in google..
Yeah... Google results differ based on your search history and what you type in.
indeed
cool
thats the virtual camera
now, you see the target
Look At
you have rotate that with camera when its in free look
does that have to do with code
yeah probably
how would I do that?
hmm maybe
CombatLookAt.transform.rotation = Camera.main.rotation
is it simmilar to this? /rotate orientation
Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);
orientation.forward = viewDir.normalized;
@potent sleet do you think it would be something like this
which one is target transform CombatLookAt
yes show this object in the scene
can you make video of it in playmode , put game tab in side by side and lemme see where it goes in playmode
ok whats the target for the freelook camera
orientation
for comabat look at you should put the target where the player is basically and rotation should be the same from the freelook camera before switching
store the rotation in a quaterion
huh?
how do i do that?
hmm probably make a script that makes that CombatLookAt follow player without being child of anything
this way you can preserve rotation
when you switch from free look to look at you pass the rotation of your current camera to that CombatLookAt
then rotate player as well with that rotation
is there any docs that can help me do that
because I have no idea how to do any of that
there are methods to do this but this isn't a docs for this
its specific to your situation
thats how coding works 😛
you can probably find a tutorial which already does this just by making this camera system
its very common anyway, im sure you inevertly bump into the correct code or find it on unity answers
I assumed you could since this is #archived-code-general not the #💻┃code-beginner 🙂
mb
void Update()
{
if(cableUsed != 0)
{
if (Input.GetMouseButtonDown(0) && qDetection.hoveringGameObject!=null)
{
structure1 = qDetection.hoveringGameObject;
}
if (structure1 != null)
{
if (!cableInstantiated)
{
cable = new GameObject("cable");
lineRenderer = cable.AddComponent<LineRenderer>();
if(cableUsed == 2)
{
lineRenderer.material = green;
}else if(cableUsed == 1)
{
lineRenderer.material = red;
}
lineRenderer.startWidth = 0.05f;
lineRenderer.endWidth = 0.05f;
cableInstantiated = true;
}
if(Input.GetMouseButtonDown(0) && qDetection.hoveringGameObject != null)
{
structure2 = qDetection.hoveringGameObject;
lineRenderer.SetPosition(0, new Vector3(structure1.transform.position.x, structure1.transform.position.y, -1));
lineRenderer.SetPosition(1, new Vector3(structure2.transform.position.x, structure2.transform.position.y, -1));
structure1 = structure2;
structure2 = null;
cableInstantiated = false;
}
else
{
lineRenderer.SetPosition(0, new Vector3(structure1.transform.position.x, structure1.transform.position.y, -1));
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
lineRenderer.SetPosition(1, new Vector3(mousePosition.x, mousePosition.y, -1));
}
}
}
}
I am using this code to place lines between game object
but when i press on the second game objct the lines stops getting rendred
found a tutorial
In this video, we’re going to look at how we can set up a third-person camera using the new Aiming Rig of Cinemachine 2.6, and how we can use Impulse Propagation and Blending to create additional gameplay functionality for our camera controller.
Download this project here!
https://on.unity.com/36nVNzt
Learn more about Cinemachine 2.6 here!
htt...
but the game object is not deleted
looks promising and it's from Unity!
solved
What values does Unity put into a web request User-Agents header?
@leaden ice I'm in a position where I can't do that lmao
y
make a RequestBin and look at the request
or you can probably just print out the request in the console
Let's say that I'm trying to mock what UnityWebRequest sends for a device which does have a Unity-specified handling of User-Agent: https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.html
i don't see why you can't Try It And See
honestly I don't know how to do this completely :x
a RequestBin?
I'll investigate trying to print to console if I can
Okay we do have UnityWebRequest.GetRequestHeader so I'll use that
how do i declare a function that uses a list as a parameter ?
void delete(<GameObject> cables) this does not work
i am stupid
solved
So since user-agent is not a custom header it returns Null to me
this works nicely
spanish?
engli
google around I'm sure you'll find one, search reddit too
Anyone ever used the Kinematic Character Controller from the asset store? (https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131#description) I have a code question about it.
It's better if you just ask your question
I need to know how to make the "Moving platform" walkthrough work without using animations and just moving the "platform" through code
The user guide should give you an example, and there should be a scene with it as well.
But quickly looking at some old code project, it looks like you need to implement the IMoverController interface, and also give your object the PhysicsMover component(?)
why does the score turhn -1
after only one collison
the intial lives is set to 3
huh what debug is that
more context i don understand
and ontriggerneter if the shape is wrong it should -1
but instead on the first wrong it goes from 3 to -1
can you add this and show new debug
Debug.Log($"{name} - Lives: {manager.lives}")
in the last else statement?
ye
how would u destroy a script from instantiated object
i tried this
but it doesnt work
what do you wanna destroy on shapeClone
component goes in the T
GetComponent<T>()
replace T with scorehandler script or w/e
oh ok
hey so this seems very basic but i cant seem to get it right im trying to make this object rotate and always face the character which is what is happening but when i start the game the position and rotation of the object is completely messed up, any reason why?
could you explain what i did wrong
The article I linked explains it in detail
im reading it i dont understand what I did wrong
i have 2 points and a speed in between getting to the points
Right, and that's not how lerp works
ok please help me and tell me what i am doing that doesnt work
because right now looking at the article i dont see my mistake
or undestand it however
You didn't read the whole article in 2 minutes
ok
a better question, would i use lerp for this scenario
based on my learning, no
and is my mistake the problem of the rotation
Just use LookAt
But yes 2 things wrong with your lerp. Improper 3rd parameter
And your start parameter is always updating. It should be cached
ok how would I replace the time.deltaTime slot bc i understand that wont ever make it to what the desired position
and how would I replace the first paramater to the position of the game object
You'd know if you actually read the article
You cache the initial rotation, then you use the cached version as the first parameter
Which is what I said here
you dont need to keep stating it im reading it
You asked,I answered
In your use case could probably use this instead though
Or RotateTowards
I forget the difference
trying to use LookAt it works the same but the rotation is still being weird
like the game object is still snapping to a different position
Can't help unless you show code
no im just rly stupid i fixed it
sry for all the confusion, I do understand Lerp correctly now tho so thank you both!
I also just remembered you can set the direction an object is facing by just doing something like this
RotatingObject.transform.forward = targetVector
@graceful rampart
Assuming the forward axis is the front
good to know Ill keep messing with it, appreciate it
Try again, and show your attempt next time
Consider going through Unity courses to learn basics. links are in the pins
screenshot the script you are trying to drag
I get it but
@swift falcon You have animator selected. You can add scripts only on game objects
screenshot the script in the project window
do you have 2 classes Player and player in one file?
this
that shows that there are 2 different classes in your script fioe. One called Player and one called player
you can only have 1 monobehaviour class in a script file
yes, i'm guessing Player is the one to delete
And then change class player to class Player
hello everyone, I wrote this method for calculating the intersection points of splines, and there was such a problem that sometimes it gives out several points instead of one at the intersections due to the fact that the distance is less than 0.01 for several points at once. Maybe there is a way to fix this?
no, the complete definition for class Player
from public class Player to public class player but not including the last line
Hi, I'm making a Race master 3d Like which in which a car basically follows a spline to follow a path but the problem is I need to give user a little control as is in original game where player can swipe and change the direction of the car while staying on the spline path and in very few cases leaves the path is there any suggestion ?
Things I have tried:
Made a Empty gameobject and made it follow spline and made the car child to that gameobject. (Didn't work as car deviates from the path more than epected or starts doing 360 flips)
This is going to be costly... Projection on a Spline is a costly operation. Instead subdivide both spline then do line-line intersection. Reduce your step also, it makes no sense to have such a small step in most scenario.
Does anyone have experience with the Unity UDP package? I've imported it into my project today and it immediately caused duplicate pre-compiled library issues. It seems to be clashing with the Unity In-App Purchasing plugin? 😦
OK, so having removed the package via Package Manager and reinstalling it. The errors are gone, that's worrying. 🙂
Why am i getting an error on this line?
if (vibscript.Vibration == true) { Handheld.Vibrate(); }
Object reference not set to an instance of an object
I have referenced it public Vibrations vibscript;
And this is my other script
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Vibrations : MonoBehaviour
{
public bool Vibration;
public void Start()
{
Vibration = true;
DontDestroyOnLoad(gameObject);
}
public void VibrationsSave()
{
Vibration = !Vibration;
}
}
`
🤨
and filled the reference in the inspector?
What do you mean
I made a gameobject and attached the vibrations script to it
if youre asking that
and now you need to drag/drop that into vibscript in it's inspector
But the vibscript is just a reference to the Vibrations script
like this?
That would be better.
So what, i drag an object to another object?
screenshot the inspector of the script that contains this line
public Vibrations vibscript;
Its quite big
sorry, the inspector of the gameobject which is using the script containing that line
Oh
I get what you mean
But the object where i need to attach the vibscript is a prefab
then you cannot do that, prefabs cannot directly reference scene objects
Dammit
Can you please rephrase your question. What do you want to achieve?
I'll see if I can help
Well
So i have a settings menu , which is in the main menu scene. There i have a toggle that switches the vibration of the Ball when it hits the hoop(On or off). I have this script
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Vibrations : MonoBehaviour
{
public bool Vibration;
public void Start()
{
Vibration = true;
DontDestroyOnLoad(gameObject);
}
public void VibrationsSave()
{
Vibration = !Vibration;
}
}
`
This void VibrationsSave attached to the toggle
But
any vs extensions that generates event handler method on += ?
I have a Ball gameobject which is a prefab and it has a ballcontrol script which is quite big to post but heres the main thing
Finally
When the ball hits the hoop
`void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.name == "WinTrigger")
{
SceneChangeTracker.counter ++;
GameObject.Destroy(wintrig);
if (vibscript.Vibration == true)
{
Handheld.Vibrate();
}
WinMenu.SetActive(true);
menubutton.SetActive(false);
celebration.Play();
}`
Object reference not set to an instance of an object
And i cant set it cuz its a prefab
Ya
No I meant when you rephrase your question you just get to the point..
doesnt make any sense, you can reference prefabs
Now you're not even telling me what's causing the null ref
prefabs cannot reference scene objects
i know
No way you went through that so quick
They call me the flash
Nevermind
I have read it before
i see, ive understood it as "i cant set the reference to it because the reference is a prefab" which didnt make sense
@sharp root So the basic solution is
once you have instantiated the prefab you need to get a reference to the Vibrations script and fill vibscript
So can you add a vibscript reference to the script that instantiates?
Look into dependency injection. It's in there
Yes
and that is also a scene object?
Yes
great, so add this
public Vibrations vibscript;
to that script then screenshot the inspector of it's gameobject
why not
Its 2 seperate scenes and the other object is a prefab as i have mentioned
you only ever have 1 Vibrations script active, correct?
ok so in the Vibrations script add
public static Vibrations vibscript;
and in the Start method
vibscript = this;
Ok i have
now in your Ball script in the start method add
vibscript = Vibrations.vibscript;
using UnityEngine;
using UnityEngine.Events;
public class ShootHitscan : MonoBehaviour
{
[SerializeField] private UnityEvent shotFired;
[SerializeField] private Transform firePoint;
[SerializeField] private float range = 10f;
[SerializeField] private PlayerInput playerInput;
[SerializeField] private Hit hit;
private Recoil recoil;
private void Awake()
{
recoil = GetComponent<Recoil>();
}
private void OnEnable()
{
playerInput.onClickEvent += Shoot;
}
private void OnDisable()
{
playerInput.onClickEvent -= Shoot;
}
public void Shoot()
{
// Check if recoil period is over
if (!recoil.InRecoil)
{
// Shoot raycast and return hit object (or null)
RaycastHit2D hit = Physics2D.Raycast(firePoint.position, firePoint.right, range);
// If the ray hit an object, check if the object is Hittable
if (hit)
{
GameObject hitObject = hit.transform.gameObject;
TryHitObject(hitObject);
}
// Enable recoil period
recoil.InRecoil = true;
shotFired.Invoke();
}
}
void TryHitObject(GameObject objectToHit)
{
if (objectToHit.TryGetComponent(out Hittable hittableObject))
{
hit.knockbackSource = transform.position;
hittableObject.TakeHit(hit);
}
}
}
I have this class which I want to make more generic. Right now it shoots a raycast, checks if it hits, then applies damage. However, looking back, the responsibility of this class should only be to shoot something (be it a raycast, or a projectile, or a mine, etc). Is this a good opportunity to make an interface?
Turn on Rigidbody interpolation
Also you'd have to show how the up and down movement works
Because MovePosition is not generally compatible with any other type of movement simultaneously
Yeah no
You can't mix velocity and MovePosition
Not really seeing the issue tbh
It seems smooth in both videos
This video should be pinned here: https://www.youtube.com/watch?v=fmbYlYU7z9Y
Actually very informative and useful.
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
Show your Support & Get Exclusive Benefits on Patreon (Including Access to tall tutorial Source Files + Code) - https://www.patreon.com/sasquatchbgames
Wishlist Veil of Maia! - https://store.steampowered.com/app/1948230/Veil_of_Maia/
Wishlist Samurado!
https://store.steampowered...
Rip, it was already posted
Some of those tips are not even Unity specific.
Is it possible to wait for end of frame in an async method? I would like to play an animation and let my Task delay for the length of the animation, however it appears that I must wait a single frame before using GetCurrentAnimatorClipInfo to get the correct length.
I usually like to keep things in scope, so it's not everywhere, however, if there's no other way, I guess that's an option.
Specifically I'm trying to make an async method that I can await to play the animation till it completes
Is there a way I can reference an unknown component and then enable/disable it from code?
Something like this:
[SerializeField] Component[] _enabled;
public void TimeChanged(bool forward)
{
foreach (Behaviour b in _enabled)
{
b.enabled = forward; // COMPILER ERROR, Component does not have "enabled" :(
}
}```
Make it a Behaviour array
I imagine this is due to the fact some components can't be disabled but is there any subclass or anything?
Ah right I tried that as well but I wasn't able to assign SpriteRenderer to it for some reason
some components are not Behaviours though
Because that's not a Behaviour!
Renderers being one example
Bit of a headache, innit
Colliders being another
I just did separate lists when I was in a similar situation
Colliders and renderers are like the two things I want lol
Depending on what you are doing, you could use https://docs.unity3d.com/Manual/StateMachineBehaviours.html to know when an animation has ended.
you could do this:
Component[] components;
foreach (Component c in components) {
if (c is Renderer r) r.enabled = true;
else if (c is Collider col) col.enabled = true;
else if (c is Behaviour b) b.enabled = true;
else { // no }
}```
Hm alright thanks
Yeah, I think I'm going to do that, using async is handy but it seems like async doesn't have any built-in wait for end of frame, thanks
Hi there, I want to do smooth NPC movement based on the new splines package. Basically I calculate path with navmesh, and then I'm creating spline based on path corners. The problem is that knots positions are local and therefore when I move the agent spline is moving as well, and It's crucial that spline component is on the NPC game object. Is there any way to switch spline to global space, or some kind of not tedious workaround to this?
Here is my path generation code:
{
NavMesh.CalculatePath(transform.position, _destination.position, _agent.areaMask, _path);
_pathCorners = _path.corners;
_spline.Clear();
for (int i = 0; i < _pathCorners.Length; i++)
{
BezierKnot bezierKnot = new BezierKnot();
bezierKnot.Position = _pathCorners[i] - transform.position;
_spline.Add(bezierKnot);
}
_spline.SetTangentMode(TangentMode.AutoSmooth);
}```
you could just deparent the object with the spline on it 🤔
I think I did that once
ah, but you said it must remain on there
One option would be to convert the world-space points back into the local space of the object
but that would make the editor visuals very confusing
the spline would be moving around
yeah, and this is exactly what I want to avoid
or maybe I should do some kind of spline manager placed in global (0,0,0), and when one particular npc creates spline it will be added to list, and npc got reference to index on that list. And making one object for all npc's should not be such a big deal
Does anyone know how to call this generation from code?
I might lean towards that.
you would probably need an editor script for that if it's at all possible
Does anyone know how to activate TMP_Text without typing anything into it? Probably just null, string.Empty or \0
define "activate"?
so I just need it to have TMP_LineInfo.lineExtents (that is 0 when it is not activated)
Yes. I Work in Editor script
what are you trying to accomplish
I am trying this method to work probably at the start (when nothing is typed yet)
private void AlignCaret()
{
if (_textInfo.lineCount == 0)
_textInfo.lineCount = 1; // lineCount is 1, but lineExtents is still Vector3.zero
TMP_LineInfo currentLine = _textInfo.lineInfo[_textInfo.lineCount - 1];
TMP_CharacterInfo charInfo = _textInfo.characterInfo[currentLine.lastCharacterIndex];
Extents extents = currentLine.lineExtents;
float middleX = (text.Length > 0) ? charInfo.xAdvance : extents.min.x;
float middleY = (extents.min.y + extents.max.y) / 2f;
caret.position = textComponent.transform.TransformPoint(new(middleX, middleY));
print(middleX + " " + middleY);
}
that's custom caret
Are you making your own input field?
What's wrong with the built in one?
alr.
sounds more work than its worth tbh
We have been talking with other people about this a few days ago
I need to make infinite Input Field
that is possible to work normaly with at least 100k characters in default conditions
I have made typing system and caret already, but it is not activated until TMP_Text has some characters in it
so is the issue just positioning the caret properly? It should be a pretty simple edge case. if (characterCount < 1) something;
I need to position it according to the textComponent's current line
first in this case
and I cannot access it's beginning
when TMP_Text does not have any characters
Well I want to automatically create a shape when saving a sprite
how do i change mouse sensitivity with a script. im making a 1st person shooter
for some reason the emissive material isnt showing up in my camera view, but is in the scene view. My guess is because my camera is so far away, but im not entirely sure. I'm using URP
Left is scene view, right is game view
create a float variable, multiply your mouse input by that float variable. adjust the float variable because it now represents the sensitivity
thank you
How can this be used for generation?
Hello everyone !
I'm curious to know. Does a tool / package exist to parse the Unity.txt log in a nice way ?
I read my log file from my build. But it's visually not appealing and parsed so.
not sure where to ask this but does anyone know where I can find all scripts that I've created in a project. There's some under assets but that's not all the one's I've used and I'd rather not search for them every time
you could search for t:script to search for every script asset
Pretty sure there are paid consoles for this, but you could also just print it to some text area yourself if you dont need it fancy
That's what I did at least, saved myself money at the cost of my sanity
Yes ! I searched for some but didn't find any after runtime.
Basically having a logger in the game is good. But I need to parse the file from the runtime build
If you have a good package to recommend I'm all ears !
Tbh I built it myself so i dont know if there is any. Doubt theres a good one for free. If you mean a package for parsing files, you can do that already just with c#
And any language pretty much
Yes ! I already did a small one in JS so it can be shared around. I hesitated doing it directly in Unity
Even if it's paid, no logger is doing that on the store right now I feel !
The one I saw was quantum console, a lot of people talk about odin though I dont really know what it does
Odin as in the serializer ? Oo.
actually idk if im remembering wrong, might not be odin. Quantum was shown in a networking tutorial where the guy was building to run multiplayer and needed it
i barely ever look at these paid packages tbh, it really shouldnt be hard to build yourself if all you want is file logging to screen
Oh I see. But quantum is a console not à log parser
Yes you're right. Just wanted to save a bit of work.
from how i saw it used, it does print the logs to console
but yea the reason its expensive is not because of this basic feature, you can add commands and view a lot of other stuff
i would just write to a different file
get the directory from that path, then write your file there
i personally just use serilog and wrote a sink for it that just fires an event when a log is sent so that i can do whatever i need to in game with it, like hook it up to an in-scene text box or something
oh maybe im misunderstanding what this was for 🤔
is it possible to use a MonoBehaviour as key to dictionary ?
GetHashCode() and Equals() , are they necessary to override in this case?
nothing special is required.
awesome, thanks!
Hey everyone im having trouble with a character selector while using addressables im really really confused
Basically the system i have in place is you select a skin and hair which are buttons. OnClick gives you a string which is the addressables Address i put that address into a class Serialize the class before a scene change and then Deserialize it OnSceneLoad() and even though the address im getting is correct it still gives me the wrong skin and hair and i for the life of me cannot figure out why its quite a bit of code if anyone is interested in helping
Hi, if there's someone who is interested with PUN (Photon) can you help me?
GetComponent<PhotonView>().Owner.NickName = "arda";
The only thing I write is this, but it gives NullReferenceExpection error.
I checked it with Debug.Log() and I found PhotonView is not null but owner is.
What can I do?
The owner of a PhotonView is the creator of an object by default Ownership can be transferred and the owner may not be in the room anymore. Objects in the scene don't have an owner.
Oh, then the thing I'm trying to do is totally wrong. What should I do to give a nickname to a player?
which player? Yourself?
ah wow that's a lot of scripts lol. You wouldn't happen to know of a way to access only one's I've edited in visual studio would you? If not do you have any tips for staying organized or should I just not be dumb and keep visual studio tabs open lmao
put your scripts in a folder.
Yes, myself and also other players which are in the same room.
putting things in a folder is only for organization and wont affect heirchy or anything right?
sorry about the noob questions I'm pretty new
PhotonNetwork.LocalPlayer
PhotonNetwork.PlayerList
wdym by folder?
In project window?
well figure out what you mean
then ask the question again
the Hierarchy displays objects that are in the current scene.
this has nothing to do with the hierarchy.
I don't know I'm going by what chemical told me
alrighty thank you
you can move assets around as much as you want without having any problems
just do it in Unity.
or move the .meta files with the actual files
I will try this, thank you so much!
if you don't keep the .meta files together, Unity will think you deleted Assets/MyScript.cs and created Assets/Scripts/MyScript.cs
neat trick: add a compile error so that unity can't recompile, then move your scripts around within unity
it'll be a lot faster than way
(otherwise, it will recompile every time you move a script asset)
that sounds a bit advanced for me idek what a meta file is but I'll keep it in mind if I do make a folder
have you ever looked around in your project in Explorer?
you will see lots of .meta files
make a folder. select all of your scripts and put them in it.
"found the folder"?
Move them within Unity.
That way, you don't even have to worry about it.
oh I was going to move the meta files and the script files together and manually create a folder called "scripts" in explorer
that would work, yes
also, are you using version control?
if not, do that before you start rearranging everything
in case you, say, decide to move the files in Explorer and don't move the .meta files
How could I run a script only after all OnCollisionXXs have been run for the "normal tick", or frame?
I saw on the docs you're supposed to use PlayerLoop to do this, but they didn't go into very much detail about how to use it or how it works.
you can use a coroutine and yield WaitForFixedUpdate that happens just after collision messages during the physics loop
Thx!
you can also check out this for more info about the order things happen: https://docs.unity3d.com/Manual/ExecutionOrder.html
for example you could technically even use Update unless what you are doing requires being on the physics time step
Im working on a Udemy class but I'd like some company since I easily lose focus/get offtask. Is there a particular voice channel that I could use to stream my work?
not in this discord
not in this server. this is also not a regular off-topic "general" channel. this is for general code issues.
you may want to check out other game dev or programming discords if you want voice channels
How can I set readable/writable setting for a runtime texture?
I see it is false by default.
To toggle this, use the Read/Write Enabled setting in the Texture Import Settings, or set TextureImporter. isReadable. By default, this is true when you create a texture from a script. Note: Readable textures use more memory than non-readable textures.
well, that documentation says that it's true by default for a texture you create from a script
By default, this is true when you create a texture from a script
I create them and save them
I want them to be readable/writable but they are not.
wanna provide relevant code so nobody has to make assumptions about what you may or may not be doing?
OK
var atlas = new Texture2D(AtlasSize, AtlasSize, DefaultFormat.LDR, TextureCreationFlags.None);
// change and set some pixels.
atlas.SetPixels(index.x, index.y, (int)rect.width, (int)rect.height, pixels);
// save it
File.WriteAllBytes($"{path}.jpg", atlas.EncodeToJPG());
My goal is to create some texture atlases and pack them into a texture array.
and is this code where the error is happening?
Texture array does not support compressed format. Also, it is required read/write textures
The error happens when creating texture array.
I know what the problem is
Just be sure, you know that Unity has Atlas built in ?
1- set read/write for textures
2- use uncompressed formats
I know
so this is not where the error is happening?
It does not handle my scenario.
I want to have size and start index for each texture in an atlas and pass them into my custom shader.
The custom shader uses a texture array of atlases.
I don't know what is your goal. My question is clear
show me the code where the error is actually happening at.
You said runtime textures is readble/writable. I see it is not.
contrary to what you apparently believe, the code i'm requesting to see is also relevant
depends what you are expecting a "root project global variable" to even mean
var atlas = new Texture2D(AtlasSize, AtlasSize, DefaultFormat.LDR, TextureCreationFlags.None);
// change and set some pixels.
atlas.SetPixels(index.x, index.y, (int)rect.width, (int)rect.height, pixels);
// save it
File.WriteAllBytes($"{path}.jpg", atlas.EncodeToJPG());
After running it, I see read/write flag is false in the editor for that texture
It creates a texture array
var sample = textures[0];
var textureArray = new Texture2DArray(sample.width, sample.height, textures.Count, sample.format, false);
textureArray.filterMode = FilterMode.Trilinear;
textureArray.wrapMode = TextureWrapMode.Repeat;
for (var i = 0; i < textures.Count; i++)
{
Texture2D tex = textures[i];
textureArray.SetPixels(tex.GetPixels(0), i, 0);
}
textureArray.Apply();
string uri = path + filename + ".asset";
AssetDatabase.CreateAsset(textureArray, uri);
AssetDatabase.Refresh();
Error is this line
AssetDatabase.CreateAsset(textureArray, uri);
Can't create asset.
your hierarchy is showing your scene (i hope at least), do you mean something like this
https://docs.unity3d.com/ScriptReference/Application-dataPath.html
I mentioned because textures are not readable/writable and uncompressed , so?
yea u arent gonna be able to take much from roblox, unity is way more complex
the default is true, however when you create a file out of the texture it is imported into the project. that is where the issue is happening. have you considered using the TextureImporter to set the isReadable property to true?
once you save it to a file as an asset in your project it isn't exactly a "runtime" texture anymore, is it?
I do not understand your meaning about they are runtime or not but yes they are created in one script (editor) and be saved to jpg files.
Thanks dude, TextureImporter
I got, runtime in unity docs means they are created and used in runtime, so they can set and get.
yes, once you save it as a file and import it into your project it gets that false value because that is the default value for textures imported as assets. in the previous code snippet where you create the texture, it is writable because you have not done anything to it to make it not writable. but that file you created is completely separate, it gets imported into the project with the value set to false. but the texture you have in memory in that code is still writable
a texture is a texture object, not an image on your disk
Are you kidding me?
A texture can be a texture asset or a texture object.