Welcome, Guest. Please login or register.

Login with username, password and session length

 
Advanced search

1411493 Posts in 69377 Topics- by 58433 Members - Latest Member: graysonsolis

April 29, 2024, 05:38:57 PM

Need hosting? Check out Digital Ocean
(more details in this thread)
TIGSource ForumsDeveloperTechnical (Moderator: ThemsAllTook)General thread for quick questions
Pages: 1 ... 32 33 [34] 35 36 ... 69
Print
Author Topic: General thread for quick questions  (Read 135559 times)
NoLocality
Level 1
*


AssetsAssetsAssetsAssetsAssets...


View Profile
« Reply #660 on: May 29, 2016, 05:49:13 PM »

So I'm about getting around to scripting a feature and a nagging feeling is creeping on that there is a better way that I'm not aware of.

Concerning Unity and C#, is anyone aware of a way to invoke scripts without calling the script itself by name?

Can you assign button 1 to execute a method from a script at one moment then execute a completely different one from a different script the next?  I've tried exploiting the parent/child object relations...(is there a child object of this object? does it contain a script? could we run a method out of that script?)...no success.  I even tried naming the scripts the same just so I could run whatever version happened to be 'present'...not my proudest moment when things 'clicked' lol.

I've been searching far and low but it seems I may just have to make an embarrassingly massive mess of switch statements and methods all within the same script...

This will likely be 100s of lines and I don't think twelve versions of this running on the update is a good idea.


I can elaborate more if this is too vague but I try not to wall of text unless necessary.
Logged

bittwyst
Level 1
*


Twitter: @bittwyst


View Profile WWW
« Reply #661 on: May 29, 2016, 07:11:14 PM »

I can think of a neat way to do it if it's different instances of the same script, but if it's different actual scripts then it would be less neat, I feel like I don't quite have the knowledge for what you want but could maybe figure it out with more info, can you elaborate?
Logged

NoLocality
Level 1
*


AssetsAssetsAssetsAssetsAssets...


View Profile
« Reply #662 on: May 29, 2016, 10:23:25 PM »

Okay I just typed out a wall of text elaborating quite a bit and it apparently was eaten by the internet when I hit the post button... Angry Angry Angry

Forgive me if this post sounds rude but I'm a bit frustrated from that and tired atm.


Shortened version of what was lost:

I may have figured this out but I have yet to test this-

Scripts themselves apparently don't like being treated like a group of variables or array elements-

I think you can pass a string variable as the name of the script you need to call upon thus you can call upon different scripts with the same button under different circumstances-

I'll explain what all this means game-wise and elaborate better tomorrow-


Thanks for reading...g'night all  Tired
Logged

BorisTheBrave
Level 10
*****


View Profile WWW
« Reply #663 on: May 30, 2016, 12:19:40 PM »

I'm rusty on Unity specifics, but you may find it easier if you stop calling scripts (a Unity only concept), and use methods and classes, which are general to C#. They're more general, but I don't think you can use them from UnityScript, just C#.

In C#, you can store a method in an Action<> or Func<>, which is handy for this sort of thing.

Code:
using System;

...

static void MyMethod1(int a, string b)
{
 ...
}

...

Action<int, string> myAction = MyMethod;

myAction(1, "asdf");
Actions and Funcs are values that can be stored and pass around like anything else, so you can do some stuff with them which is otherwise very complex to express.

The Behaviour and SendMessage system are also handy ways of doing different behaviour at different times without using big switch or if statements. Which one is most convenient depends on what you are tyring to do.
Logged
gimymblert
Level 10
*****


The archivest master, leader of all documents


View Profile
« Reply #664 on: May 30, 2016, 02:05:48 PM »

You might need to look at UnityEvents
http://docs.unity3d.com/Manual/UnityEvents.html
Logged

NoLocality
Level 1
*


AssetsAssetsAssetsAssetsAssets...


View Profile
« Reply #665 on: May 31, 2016, 02:25:57 PM »

Game wise I'm putting together a feature where the player is able to absorb abilities from enemies/environment and use them with the same button.


Player presses 1 near a volcano and absorbs three charges of molten rain-

Button one will now rain lava and decrement the remaining charges by one when pressed-

Upon the charges reaching zero button 1 once again reverts to absorption mode effectively "emptying the chamber"-

I expect twelve "chambers" for desperate buttons (though only four active at anyone time...I don't like the idea of my players hand needing to roam far from the movement keys in a keyboard setting)-


@BorisTheBrave That Action<> is pretty snazzy...I have never ran across that command and it makes sense immediately.  It reminds me of how people construct and use databases to store things like item or bullet values where it would make sense to adjust certain values to simulate like....different guns or something similar.

I.E. High frequency, high bullet speed and and a barely visible line texture would effectively recreate a machine gun...adjust down the frequency, slow the bullet speed and change the texture to a little rocket to recreate a rocket launcher...all by adjusting similar values.

The reason this won't help me in this particular instance is that the "abilities" I have in mind for my "chambers" are very different from each other...I don't expect many will have similar values or variables aside from how many charges each ability grants and perhaps an "ability  ID".

Something like...absorbing volcanos grants three charges of lava rain, absorbing pterodactyls would grant 1 charge of thirty seconds of flight, absorbing an angry mob would grants ten charges of summoning an angry caveman that would follow and assist you in battle till dead, etc...

I've been looking for a work-around to access methods from different classes without specifying the class name...

Here let me show you this bit of code I've been tossing together to test ways to achieve this, granted the whole "string variable to attempt tricking the compiler into calling upon different classes" didn't work but it shows what I'm getting at.

Class 1:
Code:

public class ChamberTest : MonoBehaviour {

private string scriptName = "Nothing";
private int charges = 0;
private bool loaded = false;

public GameObject spellHolder;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

if (Input.GetButtonDown ("O")) {
CaptureB();
}

if (Input.GetButtonDown ("I")) {
CaptureA();
}

if (charges < 1) {
loaded = false;
scriptName = "Nothing";
}

if (Input.GetButtonDown("U") && scriptName == "Nothing") {
Debug.Log (scriptName);
}
else if (Input.GetButtonDown("U") && scriptName != "Nothing"){

//scriptName loadedMagic = spellHolder.GetComponent<scriptName>()
//loadedMagic.Magic();
//charges -= 1;

Debug.Log (scriptName);
}

}


void CaptureA(){
loaded = true;
scriptName = "SpellTestA";
charges = 3;
Debug.Log ("Magic A is loaded");
}

void CaptureB(){
loaded = true;
scriptName = "SpellTestB";
charges = 5;
Debug.Log ("Magic B is loaded");
}
}

Class 2:
Code:
public class SpellTestA : MonoBehaviour {

public void Magic(){
Debug.Log("Magic A has fired!");
}
}

Class 3:
Code:
public class SpellTestB : MonoBehaviour {

public void Magic(){
Debug.Log("Magic B has fired!");
}
}

Toss classes 2 and 3 into the "spellHolder" object, child that object to the object containing class 1.

Check out the commented-out bits in the "else if" statement in class one, I was seeing if it would work to contain the names of classes 2 or 3 within the string "scriptName" and invoke methods from these using something like...scriptName loadedMagic = spellHolder.GetComponent<scriptName>()...then...loadedMagic.Magic();...no success obviously.


Honestly I think I am overthinking this a bit too much and can get away with something like this.

Code:
public class ChamberSwitchMethod : MonoBehaviour {

private int abilityID = 0;
private int charges = 0;

void Update () {

if (Input.GetButtonDown ("U") && abilityID == 0) {
//look for collision data to change the abilityID and charges appropriately
} else if (Input.GetButtonDown ("U") && abilityID != 0) {
//swtich statement to search through cases of the ability ID
//and use coresponding methods within this class
//decrement charges as needed and revert ability ID
//to absorb made should charges fall under 1
}
}

void AbsorbModeMethod (){
//absorb abilities via collision data
}

void LavaMagic (){
//rain lava
}

void SummonCavemanAlly (){
//summon an AI friend to assist with battle
}

void FlyLikeAPterodactyl (){
//fly for awhile
}
}

Now granted doing it this way the code itself will likely reach absurd lengths as more methods are added and the switch statement lengthens to accommodate new methods, but aside from when the button is pressed this doesn't look like it would be too bad a burden on the update.  Shrug


@gimymblert I hear assigning your own delegates and events is the way to go, it's nice that Unity put in a more user friendly "event system" but I've touched upon subscribing objects to your own custom events and it seems to be more...customizable I guess...to do it yourself.

Now I just need to refresh my memory on events/delegates, haven't used them (or quite a few other aspects of C#)since I started using Unity.  Thank God I kept extensive notes from the "old days" of creating visual studio abominations...this will come in handy for a completely different aspect of this game  Wink.

@bittwyst Sadly they were separate scripts/classes, but I appreciate the reaching out  Coffee
Logged

Juskelis
Level 1
*



View Profile
« Reply #666 on: May 31, 2016, 03:30:31 PM »

So I'm trying to set up RenderTextures in Unity because I want to have blood splatter that leaves a persistent trail. I've gotten the system "working" in that everything operates as it should when the RenderTextures cooperate. However, 90% of the time the RenderTextures decide to have weird nonsense within the image that can't be overwritten.


The camera I'm rendering from has the following settings:
Code:
Clear Flags: Don't Clear
Culling Mask: Splat (the layer that all of the blood lives on)
Projection: Othrographic
Size: calculated (see below)
Clipping Planes: Near: 0.3 Far 1000
Viewport Rect: 0,0 1,1
Depth: 0
Rendering Path: Use Player Settings (player settings are default)
Target Texture: Render Texture
Occlusion Culling: Y
HDR: N
Target Display: Display 1


As for the Render Texture, it has the following settings:
Code:
Size: calculated (see below)
Anti-Aliasing: None
Color Format: ARGB32
Depth Buffer: 24 bit depth
Wrap Mode: Clamp
Filter Mode: Point


The calculations are based on the parent object for the setup. I know it isn't the best solution out there, but each canvas to splatter on has its own camera+RenderTexture. The script for calculating everything is as follows:
Code:
using UnityEngine;
using System.Collections;

public class SplatRenderer : MonoBehaviour {
    [SerializeField]
    private FilterMode textureFilterMode = FilterMode.Point;

    private enum Levels { Zero = 0, Sixteen = 16, TwentyFour = 24 }
    [SerializeField]
    private Levels Depth = Levels.TwentyFour;

    private RenderTexture tex;

    private Camera cam;

    private MeshRenderer child;

    void Start()
    {
        child = GetComponentInChildren<MeshRenderer>();

        Vector3 parentScale = transform.parent.localScale;

        //make render texture that fits the object
        if (parentScale.x < parentScale.y)
            tex = new RenderTexture(Mathf.CeilToInt(parentScale.x) * 50, Mathf.CeilToInt(parentScale.y) * 100, 0);
        else
            tex = new RenderTexture(Mathf.CeilToInt(parentScale.x) * 100, Mathf.CeilToInt(parentScale.y) * 50, 0);

        //tex.Create();

        tex.DiscardContents();

        tex.filterMode = FilterMode.Point;
        tex.anisoLevel = 0;

        tex.depth = (int)Depth;

        //get camera
        cam = GetComponent<Camera>();
        cam.orthographicSize = Mathf.Min(parentScale.x, parentScale.y) / 2;

        cam.targetTexture = tex;

        child.material.mainTexture = tex;

        tex.Create();

        tex.DiscardContents(true, true);
    }
}


I'm at a loss for what is happening. Anyone have any ideas?

Here's an example:
« Last Edit: May 31, 2016, 03:43:21 PM by Juskelis » Logged

bateleur
Level 10
*****



View Profile
« Reply #667 on: June 01, 2016, 02:06:18 AM »

Looks like that section isn't being rendered at all. There are lots of possible reasons. A good way to debug the problem is to separate the question of what the camera's seeing from the render-to-texture process. Run the program in the editor and use (a copy of) your render-to-texture camera to render the screen so that you can see what it's seeing. Set the Clear Flags to "Solid Color" using some colour that doesn't appear in your scene anywhere so you can easily spot sections which aren't getting rendered.
Logged

Juskelis
Level 1
*



View Profile
« Reply #668 on: June 01, 2016, 11:53:22 AM »

Looks like that section isn't being rendered at all. There are lots of possible reasons. A good way to debug the problem is to separate the question of what the camera's seeing from the render-to-texture process. Run the program in the editor and use (a copy of) your render-to-texture camera to render the screen so that you can see what it's seeing. Set the Clear Flags to "Solid Color" using some colour that doesn't appear in your scene anywhere so you can easily spot sections which aren't getting rendered.
When I do this, the screen doesn't show the same artifacts, which makes me think that it has something to do with the render texture itself being wonky. One other thing I found out through this is that the Depth Only and Don't Clear flags seem to work only when the editor game window is set to "Free Aspect"? It doesn't seem like the two should be tied together.
Logged

Juskelis
Level 1
*



View Profile
« Reply #669 on: June 01, 2016, 08:03:28 PM »

Okay so I figured out how to fix the issue where the RenderTexture glitches out and shows garbage data from previous renders. The settings for everything are as follows:


Camera:

Text version:
Code:
Clear Flags: Depth only
Culling Mask: [whatever layers you have your splats on]
Projection: Othrographic
Size: [calculated through script]
Clipping Planes: Near: 0.3 Far 1000
Viewport Rect: 0,0 1,1
Depth: 0
Rendering Path: Use Player Settings (player settings are default)
Target Texture: [RenderTexture created in script]
Occlusion Culling: Y
HDR: N
Target Display: Display 1



RenderTexture:

Text Version:
Code:
Size: [calculated through script]
Anti-Aliasing: None
Color Format: [Default, which for me was ARGB32]
Depth Buffer: 24 bit depth
Wrap Mode: Clamp
Filter Mode: Point



For the code itself, here's the final look at it:
Code:
using UnityEngine;
using System.Collections;
using UnityEngine.Rendering;
using System.Collections.Generic;

public class SplatRenderer : MonoBehaviour
{
    [SerializeField]
    private FilterMode textureFilterMode = FilterMode.Point;

    private enum Levels { Zero = 0, Sixteen = 16, TwentyFour = 24 }
    [SerializeField]
    private Levels Depth = Levels.TwentyFour;

    [SerializeField]
    private int scaleFactor = 100;

    private RenderTexture tex;

    private Camera cam;

    private MeshRenderer child;

    private bool firstPass = true;

    void Start()
    {

        child = GetComponentInChildren<MeshRenderer>();

        Vector3 parentScale = transform.parent.localScale;

        //make render texture that fits the object
        if(parentScale.x < parentScale.y)
            tex = new RenderTexture(Mathf.CeilToInt(parentScale.x) * scaleFactor, Mathf.CeilToInt(parentScale.y) * scaleFactor, 0);
        else
            tex = new RenderTexture(Mathf.CeilToInt(parentScale.x) * scaleFactor, Mathf.CeilToInt(parentScale.y) * scaleFactor/2, 0);

        //tex.Create();

        tex.filterMode = FilterMode.Point;
        tex.anisoLevel = 0;

        tex.depth = (int)Depth;

        //tex.Create();

        //get camera
        cam = GetComponent<Camera>();
        cam.orthographicSize = parentScale.y/2;

        cam.targetTexture = tex;

        //cam.clearFlags = CameraClearFlags.Depth;

        child.material.mainTexture = tex;
    }

    void Update()
    {
        if (firstPass)
        {
            Graphics.SetRenderTexture(tex);
            Color clearColor = new Color(0, 0, 0, 0);
            GL.Clear(true, true, clearColor);
            firstPass = false;
        }
    }

    void Destroy()
    {
        tex.Release();
    }
}

Essentially, the RenderTexture was filled with garbage stuff from who knows where, so it needed to be cleared. I thought I was clearing it before with DiscardContents, but turns out that DiscardContents doesn't actually discard the contents Durr...?

So you have to do it yourself, by calling Graphics.SetRenderTexture and then GL.Clear with a transparent color. I only wanted to do it for the first pass, so I set a flag and clear the RenderTexture only once in Update.

EDIT: original version worked on my desktop but not my laptop. Changed around to be correct. Who knows if this version actually works, I have yet to find a way to reliably test it.
« Last Edit: June 02, 2016, 12:46:42 PM by Juskelis » Logged

LucasMaxBros
Level 2
**


My body is ready.


View Profile WWW
« Reply #670 on: June 06, 2016, 02:21:53 AM »

Been looking for hours, thought this would be a simple question but nobodies given an answer. How many Rooms can be made in Game Maker: Studio? Are there limits I might be unaware about?
Also I asked a question a while ago that no one answered; is there a way to make image file-sizes smaller in GM:S? Or can they only ever be saved as PNG files? Just like to know to see if I can cut down on future project file-sizes.
Thanks.
Logged

ProgramGamer
Administrator
Level 10
******


aka Mireille


View Profile
« Reply #671 on: June 13, 2016, 04:59:23 PM »

How do I make it so that my fps limiter in C++ doesn't skip a frame every second or so? It's getting really annoying to try and find a solution to something that should be a non-issue.

Edit: nvm fixed it turns out I was using 1000/60 instead of 1000.0/60.0 as my delta time which was throwing everything off.
Logged

Juskelis
Level 1
*



View Profile
« Reply #672 on: June 13, 2016, 07:55:37 PM »

Been looking for hours, thought this would be a simple question but nobodies given an answer. How many Rooms can be made in Game Maker: Studio? Are there limits I might be unaware about?
Also I asked a question a while ago that no one answered; is there a way to make image file-sizes smaller in GM:S? Or can they only ever be saved as PNG files? Just like to know to see if I can cut down on future project file-sizes.
Thanks.

You can have virtually unlimited rooms; theres no in editor limit, only practical limits, which is hard to pin down. If you have to ask that question, you probably have too many rooms and need to think of a way to simplify them to begin with.

I'm not sure of a way to cut down on image file sizes, but you can always use image coloring and the like to reduce the number of redundant images. If its only an issue on the editor side I wouldn't worry about it too much, to be honest.



On a different note, anyone know of a way to do the place_meeting scripts from GM:S in Unity, or a script that someone has written already? It would be super nice to find it premade rather than build it from scratch.
Logged

theomg
Level 0
*


View Profile
« Reply #673 on: June 14, 2016, 12:01:59 PM »

place_meeting in unity would be Physics2D.OverlapArea, this is more or less what I use in my platformers. The skin size should be adjusted if you're not using a pixel perfect setup.

Code:
 
BoxCollider2D box;
float skin = -0.5f;
public Collider2D lastCollider;

public bool CheckCollision(float xDir, float yDir, LayerMask mask)
{
    if (box == null)
        return false;
    colBounds = box.bounds;
    colBounds.Expand(skin);
    lastCollider = Physics2D.OverlapArea(new Vector2(colBounds.min.x + xDir, colBounds.min.y + yDir), new Vector2(colBounds.max.x + xDir, colBounds.max.y + yDir), mask);
    if (lastCollider == null)
        return false;
    return true;
}
Logged
oahda
Level 10
*****



View Profile
« Reply #674 on: June 14, 2016, 12:16:38 PM »

Actions and Funcs
I never understood why it has both of these and delegates. What's the difference between the three?
Logged

BorisTheBrave
Level 10
*****


View Profile WWW
« Reply #675 on: June 14, 2016, 01:10:57 PM »

Quote
I never understood why it has both of these and delegates. What's the difference between the three?
Mostly because Action/Func was introduced in a later version of C#. I think delegates were more necessary before generics were introduced. Actions and Func only differ from each other by return type - Action returns "void", Func requires you to specify the return type.

I tend to use Action/Func all the time, and never use delegates. That said, a key difference is that delegates are distinct named types, while Action/Func is just a type signature, so sometimes it's nice to use a bit of clarify in your API. Like how you might have a type "Meter" rather than just using "float" all over the place.

Delegates can also handle out and ref arguments, which you cannot do with Action/Func, but who cares?
Logged
voidSkipper
Level 2
**


View Profile
« Reply #676 on: June 14, 2016, 03:25:49 PM »

Offhand, does anyone have a list of image hosting sites that don't downsample, resize or otherwise compress submitted PNGs?
Logged
Juskelis
Level 1
*



View Profile
« Reply #677 on: June 14, 2016, 06:17:29 PM »

place_meeting in unity would be Physics2D.OverlapArea, this is more or less what I use in my platformers. The skin size should be adjusted if you're not using a pixel perfect setup.

You da best  Beer! Hand Thumbs Up Right
Logged

oahda
Level 10
*****



View Profile
« Reply #678 on: June 14, 2016, 09:34:51 PM »

Offhand, does anyone have a list of image hosting sites that don't downsample, resize or otherwise compress submitted PNGs?
http://imgur.com/

(unless possibly if the image is extremely high-resolution, but that's not a problem I generally have)
Logged

zilluss
Level 1
*



View Profile
« Reply #679 on: June 15, 2016, 12:04:10 AM »

Quote
I never understood why it has both of these and delegates. What's the difference between the three?
Mostly because Action/Func was introduced in a later version of C#. I think delegates were more necessary before generics were introduced.

Delegates and generics are two different concepts, which were both introduced in C# 2.0.

To answer the initial question:
Delegates are C#'s "function pointers". So Action and Func are delegates that are predefined in the .NET Library. The Action/Func delegates makes sense if you view your code as a collection of messages and queries, in which an "Action" is a message and "Func" is a query. Actions change state or message other "services" to execute a specified action. Funcs query state. You can theoretically use Funcs as messages, but that would go against the concept. I couldn't find an article about this topic but it's covered in ISBN-13: 978-0321503626 if anyone is interested.
Logged

@zilluss | Devlog  Hand Point Right
Pages: 1 ... 32 33 [34] 35 36 ... 69
Print
Jump to:  

Theme orange-lt created by panic