Category Archives: Uncategorized

Use function from other script

Other script is named WordDictAdd.cs, and has a function called FillDictionary().

protected WordDictAdd dict;

void Start()

    {   
        dict = new WordDictAdd();
        dict.FillDictionary();

}

This allows me to call up a dictionary (named WordDict in WordDictAdd.cs), in this script called:   dict.WordDict 

dict.WordDict[])

 

Contents of WordDictAdd.cs below:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class WordDictAdd : MonoBehaviour {
    public Dictionary<string, string> WordDict = new Dictionary<string, string>();

    public void FillDictionary()
    {
        WordDict.Add(gug, Trash);
        WordDict.Add(hug, Notebook);
        WordDict.Add(bug, Notebook);
        WordDict.Add(plug, Notebook);
        WordDict.Add(wug, Trash);

        // this feels like a hack 
        WordDict.Add(Trash, Notebook); // so that I can find out which one it DIDNT hit
        WordDict.Add(Notebook, Trash); // above

        // new list of words  how do I want to store and access these?  in external thing ? 
        WordDict.Add(sug, Trash);
        WordDict.Add(tug, Notebook);
        WordDict.Add(pug, Notebook);
        WordDict.Add(zug, Trash);
//        WordDict.Add(wug, Trash);

    }

So now my next task is to pull in lines read-in from the big .txt file from GameManager.cs (the file that reads in the .txt) to fill up WordDict in WordDictAdd.cs . [There’s also an argument to be made for NOT having 3 interlocking scripts here.  #todo I should come back and  streamline how this is working structurally. In the meantime, I’ll just get it working.]

Actually, in the spirit of getting it working, I’m gonna read in from the .txt in this script too.  #todo – have just one script that reads in from the .txt, and then call from that in the other scripts.

Huh.  Wanting to add a column to my .txt file, and it looks like editing it in Monodevelop is not getting the ‘\t’ across to the script.  GoogleDrive also doesn’t export to .txt, so this is weirdly not working.  I want .txt instead of .csv because I’m using commas in lots of my strings that I’m pulling in.

It looks like adding dictionary entries to a dictionary from a separate script isn’t actually working.  Hmmm.   Not really sure what to do with that.  There must be a way to make this work?

Holy cow I just spent forever fiddling with this and it turns out … I got tricked by the spaces again!  Aghhh I’m so used to not thinking of spaces as meaningful unless there are quotes around them.  It was reading in my dictionary key as “chug” (correct) and the value as ” Trash” (incorrect – supposed to be “Trash”).  Oof.  Just spent like … 1-2 hours on it?  But fixed it !  Yayyyyyy

 

Converting string to int

Somehow this is really tricky!  C# websites keep saying to use int.Parse() and int.TryParse(), and Convert.ToInt32().   But my Unity isn’t recognizing these as real functions.

http://forum.unity3d.com/threads/convert-string-to-int-in-c.58867/

Ah.  Apparently I was missing Using System; . http://answers.unity3d.com/questions/61646/converttoint32-does-not-work-get-error.html

Also, I can’t do anything recursive here, because listName has already been defined as a string, and can’t be switched to be an integer type.  I see!

            private string listName;


            listName = columns[0];
//            listOnsets = columns[1];
//            listName = int.Parse(listName);

            int test = 0;

            listName =int.Parse(listName);

So I fixed that and put “test =int.Parse(listName);” – buuuut the whole thing is still mad at me, and I can’t figure out why.  Oh dear.  It’s because I forgot about my header.  #todo – figure out how to deal with headers in csv tables.  In the meantime, I’m going to cheat and delete it off my original csv file. #todo – I switched these to .txt format, so rephrase my posts about them.

Using text from .csv TextAsset

This one’s currently in progress, so it looks quite messy.  Below are things I’ve been reading about.  I have a few other solutions that are working for me right now, but they don’t recognize column names yet.

Note: Excel will mess you up.  It just will.  Something about how my Excel is exporting to .csv is making Unity unable to interpret ‘\n’, so that’s bonkers.  Excel also adds a ” for every ” you have.  Why?  Dunno.  Apparently it’s supposed to.  My computer friend recommended I switch to Google Sheets (spreadsheets under google docs) and never look back.

 

 

 

This youtube video describes how to use CSV2Table, a free asset in the asset store.

This post is by a professional female game developer.

Dumb problem I’m having with .csv out of excel is that it’s doubling up quotation marks.  Sigh.  Gonna brute force this and findall and replace with what I want, but I don’t like it.

http://answers.unity3d.com/questions/141782/how-do-i-read-read-from-and-write-to-a-text-file.html

 

http://stackoverflow.com/questions/29680181/first-read-in-prefab-name-from-a-text-file-getting-instantiated-to-null

http://superuser.com/questions/867101/excel-adds-double-quotes-on-csv-export

 

http://answers.unity3d.com/questions/782965/reading-data-from-a-csv-file.html

Ooh this one looks like it might be helpful : http://www.michaeljohnstephens.com/devblog/creating-storing-and-loading-levels-with-text-files-in-unity

I keep reading about StreamReader and StringReader, but neither of them are in the documentation for the version of unity I’m using (5.4b).

#todo – write up: if I select text and then paste a url, it automatically puts a link in.

Making a list to fill up my textmesh

Problem: I want to assign textmesh components using a script, not by interacting manually with the object.  I have 4 objects, named “1,” “2,” “3,” and “4,” all tagged as “Onset,” and all children of an otherwise empty game object.

  1. First I set up a list of gameobjects to hold everything with the tag “Onset.”

private GameObject[] onsets;

onsets = GameObject.FindGameObjectsWithTag(Onset);

2) Then I make a string list of the strings that I want to be in each object.

TIL: Apparently single quotes vs. double quotes matters here.  I believe that single quotes are for characters, double quotes are for strings.  Never really distinguished the two before!

string[] letters = {p, s, t, z};

3) Then I make a function that iterates through each gameobject in onsets, and assigns it a new index from the string list.

Holy cow this works and replaces my letters:

 void SetupOnsets()
    {
        int count = 0;
        string[] letters = {p, s, t, z};
        foreach (GameObject onset in onsets) // foreach (GameObject player in highlights)
        {
            TextMesh onsetText = onset.GetComponent<TextMesh>();
            onsetText.text = letters[count].ToString();
            Debug.Log(letters[count]);
            count += 1;

        }

 

Great! Now that I’ve got that, I can think about more complicated things, like … don’t I really want this list in a .csv that unity reads in, so that I can have many lists and organize them better. That’ll be the next post [#todo insert link]

 

http://forum.unity3d.com/threads/string-array-in-c.41399/

 

Prevent player from leaving screen – in progress

Still haven’t made this work in the way I want to.  Current notes:

 

Several options:

  1. Add a wall around the screen using 3D cube objects.  However,  one of the objects needs a non-kinematic rigid body.  I need each of my player objects to be kinematic, so that they don’t spin around when they collide with things.  http://answers.unity3d.com/questions/216204/objects-pass-through-each-other.html
  2. Include in script with collider triggers.

I’ve seen this work really easily in the roll-a-ball unity tutorial, and can’t figure out what’s different about that and what I’m doing.

 

  1. limit player’s movement space
  2. reposition when it hits a box
  3. make it not kinematic
  4. limit mouse’s movement space

Mathf.Clamp

 

 

http://docs.unity3d.com/Manual/LayerBasedCollision.html

http://answers.unity3d.com/questions/414362/keep-character-inside-of-an-objects-bounds.html

 

http://answers.unity3d.com/questions/623959/how-to-keep-object-from-going-off-screen.html

This video looks helpful:

http://stackoverflow.com/questions/26789457/characters-passing-through-objects-unity3d

 

Clone object

I don’t want to instantiate a prefab, I want to duplicate the exact gameobject I have the script attached to.

Apparently other people have thought about this and don’t love instantiating non prefabs, but can do it:  http://answers.unity3d.com/questions/957617/how-to-clone-a-gameobject-in-runtime-not-with-inst.html

I don’t want a hidden “original” one because I’ve got too many things popping in and out of my script already.  I’d really like to clone it at an exact moment in the game state, before I reset the original object to have no audio components.

Here’s what I’ve tried so far:

private GameObject answerClone;

Vector3 clonePosition = new Vector3(0, 0, 0);

answerClone = Instantiate(gameObject, clonePosition, Quaternion.identity);

 

I also tried  :

answerClone = Instantiate(this.gameObject, clonePosition, Quaternion.identity);

Both get this error.

Assets/Scripts/PlayerFinalWord.cs(172,13): error CS0266: Cannot implicitly convert type `UnityEngine.Object’ to `UnityEngine.GameObject’. An explicit conversion exists (are you missing a cast?)

 

Ah, so I need to explicitly cast this as a gameobject.  This site showed me how: http://answers.unity3d.com/questions/254195/c-cast-object-to-gameobject-not-working.html

This code now does the trick:

GameObject answerClone = (GameObject)Instantiate(answer, clonePosition, Quaternion.identity);

However,  I don’t see the object on my screen , because it’s still being affected by the commands to its original object, “answer”.  uh oh.

Things I’m reading that haven’t inspired me but might have the right answer:

http://gamedev.stackexchange.com/questions/77544/scripts-wont-affect-clones-unity3d

http://gamedev.stackexchange.com/questions/77544/scripts-wont-affect-clones-unity3d

http://answers.unity3d.com/questions/781985/how-to-spawn-prefab-to-a-certain-position.html

Maybe I really do need an early invisible OTHER answer.  Ugh.  So many invisible things running around, spawning other invisible things!   I guess I need to just create an entirely new game object and give it the TextMesh and AudioSource components of Answer at the right moment in time.

Alright so I made an empty gameobject with 3 children: NotebookEntryOne, NotebookEntryTwo, and NotebookEntryThree.  When a word gets put into the notebook, it’ll go through and index the children, and keep count.  This makes use of a code I’ve used before, to make an object have a yellow border around it from a yellow child object:

endingHighlight = ending.gameObject.transform.GetChild(0);

So here it is:

            if (other.tag == Notebook)
            {
                Transform notebookOne = (Transform)notebookEntries.gameObject.transform.GetChild(notebookCount);
                notebookOne.transform.position = new Vector3(notebookOne.transform.position.x, notebookOne.transform.position.y, 5f);
                TextMesh notebookOneText = notebookOne.GetComponent<TextMesh>();
                notebookOneText.text = thisText.text;
                notebookCount += 1; 
            }

Problems that happened on the way:

  • I forgot that GetChild returns a Transform
  • forgot that I need .text after a TextMesh to convert it from a Textmesh to a string
  • forgot the “new” in front of my Vector3 – easy fix
  • Note that I’m just moving the entry from behind the notebook image to in front of it (with the z transform.position changing from 10 to 5).

I’m super excited about this – looks kind of like magic!  Now to do the same for the other possible slot that answers can end up in – the garbage!

End game when all objects gone

I’ll of course have other things happen for the “game over” state, more like “you won!” and “next level!”, but I wanted a quick easy way to show that the code was working.

    private GameObject[] onsets;

 

    public void AddScore (int newScoreValue)
    {
        score += newScoreValue;
        UpdateScore();
    }

    void UpdateScore()
    {
        scoreText.text = Score:  + score;
        onsets = GameObject.FindGameObjectsWithTag(Onset);
        if (onsets.Length == 0)
        {
            scoreText.text = game over!;
        }
    }

The other option was to do a count for how many times the score got increased, but that would need to be reset if I wanted there to be more or fewer onsets in the game.  I like the version that checks if there are any left, and if there aren’t, declares the game done.


Adding text (scoremanager 1)

Turns out the simplest way to add UI text *isn’t* Canvas/text.

From https://unity3d.com/learn/tutorials/projects/space-shooter/counting-points at :26 :

guitext

[note – .tiff images don’t work here, but .png does.  “Add Media” button at the top left]

This also looks like it solves the fuzziness problem of TextMesh.  But it’s drawn on a layer ABOVE the game, not in the game world, so I can’t see it in the game view.  Viewport Space, rather than Screen Space.  Screen Space is pixels – Viewport space is a single width and height value (0,0 in lower left, 1,1 in upper right).   This makes it less desirable for to put on a game object, and doesn’t really seem like its purpose, but I’ll try later anyhow.

I’m liking this tutorial bc it goes through how to call a function on another component in a different game object (like I was thinking about in this post).

 

#todo – test out other objects with this, update relevant posts with this

#todo – when do you use UI Canvas vs. adding a TextUI component to an obect?  UI Canvas was really hard to place position-wise, had fuzzy text, and needed alterations to its settings so the camera could see it.

UI Canvas not showing in game view

UI elements in a canvas don’t show up in your main camera unless you change the setting.  Click on Canvas, look at the Canvas component, and switch Render Mode to “World Space” instead of the automatic “Screen Space – Overlay”.

http://answers.unity3d.com/questions/835737/gameobjects-added-to-canvas-do-not-show-in-game.html